如何在Android中发出POST HTTPs(带JSON)请求?

时间:2016-01-21 11:27:26

标签: android https

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

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

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

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

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我在研究了在我的案例中是否可以安全使用之后最终使用了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();
}
}
相关问题