Android 使用 OkHttp 进行网络请求之 POST json数据 作者: Chuwen 时间: 2020-07-12 分类: Android # 相关代码 > 只是避免遗忘,然后记录下的,具体还是要自己去搜索 ``` OkHttpClient okHttpClient = new OkHttpClient(); //指定媒体类型 MediaType mediaType = MediaType.parse("application/json"); RequestBody requestBody = RequestBody.create(mediaType, json); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { SetSuggesRes = response.body().string(); Log.d("请求成功", SetSuggesRes); /** * 在Ui线程更新UI */ runOnUiThread(new Runnable() { @Override public void run() { requestDialog.hide();//隐藏那个加载对话框 try { JSONObject resObj = new JSONObject(SetSuggesRes); if (resObj.getString("RESULT").equals("S")) { showNormalDialog("意见反馈", "意见反馈成功!", 1); } else { showNormalDialog("意见反馈", "意见反馈失败,原因:" + resObj.getString("ERRMSG").toString(), 2); } } catch (JSONException e) { e.printStackTrace(); showNormalDialog("意见反馈", "意见反馈失败,原因(远程服务器返回内容不符合预期):\n" + e.getMessage().toString(), 2); } } }); } @Override public void onFailure(Call call, final IOException e) { Log.d("请求失败", e.getMessage().toString()); runOnUiThread(new Runnable() { @Override public void run() { requestDialog.hide(); showNormalDialog("意见反馈", "意见反馈失败了,原因:\n" + e.getMessage(), 2); } }); } }); ``` 标签: Android