当前位置: 代码迷 >> 综合 >> 解决 OKHTTP 返回 Response 乱码问题
  详细解决方案

解决 OKHTTP 返回 Response 乱码问题

热度:12   发布时间:2023-11-17 10:46:19.0

下午调试一个 H5 支付 。数据那边一直出问题 。

 

 

直接上代码

   OkHttpClient mOkHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS)//设置读超时.writeTimeout(5, TimeUnit.SECONDS)设置写超时.connectTimeout(15, TimeUnit.SECONDS)//设置连接超时.retryOnConnectionFailure(true)//是否自动重连.build();RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("pay_amount", pay_amount).addFormDataPart("pay_applydate",pay_applydate).addFormDataPart("pay_bankcode",pay_bankcode).addFormDataPart("pay_callbackurl", pay_callbackurl).addFormDataPart("pay_memberid", pay_memberid).addFormDataPart("pay_notifyurl", pay_notifyurl).addFormDataPart("pay_orderid", pay_orderid).addFormDataPart("pay_md5sign", pay_md5sign).addFormDataPart("pay_attach", pay_attach).addFormDataPart("pay_productname", pay_productname).build();Request request = new Request.Builder().url(" http://47.244.131.97:8081/Pay_Index.html").method("POST", requestBody).addHeader("Content-Type", "application/x-www-form-urlencoded").addHeader("User-Agent", "PostmanRuntime/7.22.0").addHeader("Accept", "*/*").addHeader("Cache-Control", "no-cache").addHeader("Postman-Token", "f4803fbd-8773-4788-a86e-3843a9f39469").addHeader("Host", "47.244.131.97:8081").addHeader("Accept-Encoding", "gzip, deflate, br").addHeader("Cookie", "PHPSESSID=v182qe7rv0tk5mqqmk470ia2m6").addHeader("Content-Length", "1345").addHeader("Connection", "keep-alive").addHeader("application/x-www-form-urlencoded","charset=utf-8").build();Call call = mOkHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.d("onResponse111",response.body().string()+"--"+ response.body().contentType());Gson gson=new Gson();BYJHBean byjhBean = gson.fromJson(response.body().string(), BYJHBean.class);Intent intent=new Intent(context,WebViewActivity.class);intent.putExtra("name",byjhBean.getPay_url()+"");Looper.prepare();context.startActivity(intent);Looper.loop();}});

返回数据打印。

 

原因是在 addHeader 的时候 ,下面这行代码导致

.addHeader("Accept-Encoding", "gzip, deflate, br")

 

 

PS:因为浏览器在传输数据量比较大的时候会采用压缩的方式,但接收的时候没有解压所以就会出现乱码。

 

注释点上述代码就可以。

  相关解决方案