okhttp 遇到的Content-Type 自定义设置问题
- 有些接口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