com.squareup.okhttp3:okhttp:4.9.0 post上傳map參數(shù)

并沒有找到直接上傳map參數(shù)的方法,常用的post請(qǐng)求如下

 OkHttpClient client = new OkHttpClient();
//設(shè)置body 但是這里只能傳遞sting類型的數(shù)據(jù)
        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數(shù)據(jù)
                JsonObject jsonObject = new JsonParser().parse(res).getAsJsonObject();
        });

上述方法是普通的post請(qǐng)求,涉及到要傳遞map類型的,需要按照以下方式寫

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

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("hId","1203");;
        paramMap.put("payMethods", priceMap);
       
        OkHttpClient client = new OkHttpClient();
 //設(shè)置json的數(shù)據(jù)傳輸格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
 //整理出來body傳遞。但是這里有個(gè)問題就是   FormBody.create 已經(jīng)被棄用,可是又沒有找到可代替的方法,而且程序能正常運(yùn)行
        RequestBody requestBody = FormBody.create(mediaType, gson.toJson(paramMap));
//發(fā)起請(qǐng)求這里還和之前的一樣
        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("成功返回的數(shù)據(jù)", "onResponse: " + res);
            }
        });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容