安卓okHTTP之POST请求


private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8);

new Thread(new Runnable() {
     
    @Override
    public void run() {
     
        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject = new JSONObject(); // 参数
        try {
     
            jsonObject.put("nickname", "test");
        } catch (JSONException e) {
     
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        Request request = new Request.Builder()
                .url(“httpUrl/api")
                .post(body)
                .build();
        try {
     
            Response response = client.newCall(request).execute();//发送请求
            try {
     
                JSONObject result = new JSONObject(response.body().string());
            } catch (Exception e) {
     
                e.printStackTrace();
            }
        } catch (Exception e) {
     
            e.printStackTrace();
        }


    }
}).start();

你可能感兴趣的:(学习笔记)