栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

okhttp 遇到的Content-Type 自定义设置问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

okhttp 遇到的Content-Type 自定义设置问题

okhttp 遇到的Content-Type 自定义设置问题
  1. 有些接口Content-Type 必须设置application/json,但是okhttp 会自动加上 charset=utf-8
    看一下源码
requestBody = RequestBody.create(MediaType.parse("application/json"), json);
  public static RequestBody create(@Nullable MediaType contentType, String content) {
    Charset charset = UTF_8;
    if (contentType != null) {
      charset = contentType.charset();
      if (charset == null) {
        charset = UTF_8;
        contentType = MediaType.parse(contentType + "; charset=utf-8");
      }
    }
    byte[] bytes = content.getBytes(charset);
    return create(contentType, bytes);
  }

3 如果不需要加上charset=utf-8 json 需要转换成ByteString

 ByteString byteString =
                                    ByteString.encodeUtf8(json);
                            requestBody = RequestBody.create(MediaType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), byteString);
  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);
      }
    };
  }

使用ByteString 就可以使用定义的Content-Type

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946411.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号