okhttp3请求时headers设置细节问题Content-Type

使用

FormBody body = new FormBody.Builder()

时,headers中的

"Content-Type","application/x-www-form-urlencoded;"
设置不了,导致有些参数请求异常返回

使用以下方式即可,该问题非常坑人,找了好久的问题,最后抓包一行一行看才发现headers设置未生效。
public static final MediaType JSON
    = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

这样使用即可

posted @ 2021-11-10 17:06  sunny开始学坏  阅读(4236)  评论(0编辑  收藏  举报