在做项目的时候,后台需要对数据内容进行鉴权。
鉴权刚开始一直不通过,对方设定的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()
尝试成功!