• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

okhttp Content-Type 修改问题

武飞扬头像
杨忆
帮助1

在做项目的时候,后台需要对数据内容进行鉴权。
鉴权刚开始一直不通过,对方设定的Content-Type必须是"application/json"才可以。但是使用okhttp上传upjson的时候会默认增加"charset=utf-8"字符集,也就是Content-Type变成了"application/json;charset=utf-8"。导致了接口一直不能通过鉴权。
尝试1:使用upString方法。

post(url).headers(httpHeaders).upString(data, MediaType.parse("application/json")).execute

但是还是带上默认的"charset=utf-8",尝试失败。
虽然不生效,但是还是说明一下这个地方可以使用常用的参数

public static final MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8");
public static final MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");

尝试2:自定义上传requestbody

 public static MediaType JSON = MediaType.parse("application/json");
 RequestBody body = RequestBody.create(JSON, data);

post(Ur).headers(httpHeaders).upRequestBody(body).execute()

但是还是带上默认的"charset=utf-8",尝试失败。

看源码才知道,也会默认加上"charset=utf-8"

  /**
   * Returns a new request body that transmits {@code content}. If {@code contentType} is non-null
   * and lacks a charset, this will use UTF-8.
   */
  public static RequestBody create(@Nullable MediaType contentType, String content) {
    Charset charset = Util.UTF_8;
    if (contentType != null) {
      charset = contentType.charset();
      if (charset == null) {
        charset = Util.UTF_8;
        contentType = MediaType.parse(contentType   "; charset=utf-8");
      }
    }
    byte[] bytes = content.getBytes(charset);
    return create(contentType, bytes);
  }
学新通

尝试3:自定义requestBody由源码得知还有一种构造方式。就是将String转换为ByteString,就不会增加"charset=utf-8"

  /** Returns a new request body that transmits {@code content}. */
  public static RequestBody create(
      final @Nullable MediaType contentType, final ByteString content) {
    return new RequestBody() {
      @Override public @Nullable MediaType contentType() {
        return contentType;
      }

      @Override public long contentLength() throws IOException {
        return content.size();
      }

      @Override public void writeTo(BufferedSink sink) throws IOException {
        sink.write(content);
      }
    };
  }
学新通

代码如下:

 public static MediaType JSON = MediaType.parse("application/json");
     ByteString byteString =
                ByteString.encodeUtf8(data);
        RequestBody body = RequestBody.create(JSON, byteString);
post(Ur).headers(httpHeaders).upRequestBody(body).execute()

尝试成功!

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbhjie
系列文章
更多 icon
同类精品
更多 icon
继续加载