com.squareup.okhttp3:okhttp:4.9.0 post上传map参数

并没有找到直接上传map参数的方法,常用的post请求如下

 OkHttpClient client = new OkHttpClient();
//设置body 但是这里只能传递sting类型的数据
        RequestBody body = new FormBody.Builder()
                .add("pid","123").build();
        Request request = new Request.Builder()
                .url("http://xxxxxxxx")
                .post(body).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                StringMsgHandle.showToastMsg("获取信息失败",getApplicationContext());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("TAG", "onResponse: " + res);
//获得json数据
                JsonObject jsonObject = new JsonParser().parse(res).getAsJsonObject();
        });

上述方法是普通的post请求,涉及到要传递map类型的,需要按照以下方式写

        Map priceMap = new HashMap<>();
        priceMap.put("fee_ydzf","anyType");

        Map paramMap = new HashMap<>();
        paramMap.put("hId","1203");;
        paramMap.put("payMethods", priceMap);
       
        OkHttpClient client = new OkHttpClient();
 //设置json的数据传输格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
 //整理出来body传递。但是这里有个问题就是   FormBody.create 已经被弃用,可是又没有找到可代替的方法,而且程序能正常运行
        RequestBody requestBody = FormBody.create(mediaType, gson.toJson(paramMap));
//发起请求这里还和之前的一样
        Request request = new Request.Builder()
                .url(UrlString.getOrderInfo)
                .post(requestBody).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                StringMsgHandle.showToastMsg("失败!",getApplicationContext());
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("成功返回的数据", "onResponse: " + res);
            }
        });

你可能感兴趣的:(com.squareup.okhttp3:okhttp:4.9.0 post上传map参数)