【问题标题】:How to make a POST HTTPs (with JSON) request in Android?如何在 Android 中发出 POST HTTPs(使用 JSON)请求?
【发布时间】:2016-01-21 11:27:26
【问题描述】:

我正在寻找一种如何在 android 中发出 POST(登录)https 请求的方法。如何确保代码不信任自签名/无效证书。请求的输入需要采用以下格式:

{
"udid": DEVICE_ID
"email": "email@email.com",
"password": "password"
}

我需要对这种地址格式进行身份验证调用:

https://api.ADDRESS.com/v1/auth

请注意,我想使用 HTTPs 请求而不是 HTTP。

【问题讨论】:

  • 它不是重复的,因为我想使用 HTTPs 而不是 HTTP...
  • 好的,但是应该和你的 API 分别获取 http https 一样
  • 我不确定它是否相同。我需要生成证书才能建立安全的 HTTPS 连接,但我不知道该怎么做……
  • 你为什么不去支付证书(例如 Comodo),安装它们并像往常一样调用你的 api?您不需要自己生成 CA。还是我误会了?

标签: android https


【解决方案1】:

您可以使用 volley/retrofit 库来解析 json。

示例@ http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

【讨论】:

  • 我想使用 OkHTTP 库,因为它没有您建议的那么复杂。
【解决方案2】:

在研究了在我的情况下使用 OkHTTP 是否安全后,我最终使用了 OkHTTP:

public class MainActivity extends AppCompatActivity {
public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");
private static final String TAG = MainActivity.class.getSimpleName();
private JSONObject responseJson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);



final JSONObject myJson = new JSONObject();
try {
    myJson.put("udid","c376e418-da42-39fb-0000-d821f1fd2804");
    myJson.put("email","email
    myJson.put("password","password");
} catch (JSONException e) {
    e.printStackTrace();
}

    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                //Your code goes here
               String response =  post("https://ADDRESS/v1/auth", myJson.toString());
                responseJson = new JSONObject(response);
                String message = responseJson.getString("message");
                String token = responseJson.getString("token");
                Log.d(TAG,"Response message: " + message);
                Log.d(TAG,"Response token: " + token);
                Log.d("MainActivity",response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

}

String post(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}

【讨论】:

    猜你喜欢
    • 2013-02-01
    • 2011-05-12
    • 1970-01-01
    • 2011-05-14
    • 2011-05-11
    • 1970-01-01
    • 2018-03-26
    • 2011-08-17
    • 1970-01-01
    相关资源
    最近更新 更多