okhttp post用json传递参数

//请求显示数据
    private void getdata() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
添加一个json格式数据
                    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                    JSONObject json = new JSONObject();
                    try {
                        json.put("serialNumber", serialNumber);
                        json.put("pageNum", pageNum);
                        json.put("pageSize", pageSize);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //1 . 拿到OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建一个RequestBody(参数1:数据类型 参数2传递的json串)
                    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                    //3 . 构建Request,将FormBody作为Post方法的参数传入
                    Request request = new Request.Builder()
                            .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/getChatInfoByPage")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    getfeedback(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //一个JSON对象——JSONObject{}
            //一个JSON数组——JSONArray[]
            private void getfeedback(String responseData) {
                try {
                    JSONObject jsonObject1 = new JSONObject(responseData);
                    JSONArray jsonArray = jsonObject1.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        //消息内容
                        String message = jsonObject.getString("message");
                        //消息类型(0:文本;1:图片;;2:系统)
                        String type = jsonObject.getString("type");
                        //0:未读;1:已读
                        String read = jsonObject.getString("read");
                        //消息来源(0:用户;1:平台)
                        String source = jsonObject.getString("source");
                        // 创建时间
                        long createTime = jsonObject.getLong("createTime");
                        myFeedbackDetailsModel.add(new MyFeedbackDetailsModel(message, type, read, source, createTime,null,null,null));
                    }
                    send_message = Message.obtain();
                    send_message.what = 100;
                    handler.sendMessage(send_message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

相关推荐