问题描述
考虑以下代码:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("text/plain; charset=utf-8"); // [A]
RequestBody body = RequestBody.create(mediaType, media);
String[] aclHeader = "x-goog-acl:public-read".split(":");
Request request = new Request.Builder()
.addHeader("Content-Type", "text/plain") // [B]
.addHeader(aclHeader[0], aclHeader[1])
.url(url)
.put(body)
.build();
Response response = client.newCall(request).execute();
我正在使用以前签名的URL从客户端访问GCS.
I am accessing GCS from a client, with a previously signed URL.
问题:似乎okhttp也将为正文[A]声明的字符集也添加到URL中(至少对于文本/纯文本而言),即使未在[B]中声明也是如此.这会弄乱我签名的URL,GCS会返回403 Forbidden.
Problem: It seems okhttp adds the charset declared for the body [A] to the URL as well (at least for text/plain), even though it is not declared in [B]. This messes up my signed URL and GCS returns 403 Forbidden.
- 如果我从[A]中删除了字符集,它仍会添加.
- 如果我在对字符集进行签名之前将其添加到已签名的URL中,则该字符集将起作用并且GCS会返回200 OK.
但这不是应该的.至少在使用签名的URL时,这些URL必须完全按照声明的方式发送到服务器.
But this is not as it should be. At least when working with signed URLs, these must be sent to the server exactly as declared.
我尝试使用Apache http客户端(我不想在生产中使用它,因为okhttpclient已经是我的安装的一部分),并且该客户端没有暴露此行为:
I tried using the Apache http client (which I don't want to use in production as okhttpclient is already part of my installation) and that client does not expose this behavior:
String[] aclHeader = "x-goog-acl:public-read".split(":");
StatusLine statusLine = Request
.Put(url)
.addHeader("Content-Type", "text/plain")
.addHeader(aclHeader[0], aclHeader[1])
.bodyByteArray(media)
.execute().returnResponse().getStatusLine();
是否有一种方法可以抑制okhttp中的行为,即将其添加到Content-Type或在体内冗余地传输Content-Type?
Is there a way to suppress the behavior in okhttp, that it adds to the Content-Type or transfers the Content-Type within the body redundantly?
推荐答案
我找到了解决方法:
以下是罪魁祸首:
RequestBody body = RequestBody.create(mediaType, media);
create具有3个媒体签名:
create has 3 signatures for media:
- 字符串
- byte []
- 文件
当我传递一个String时,它会忽略提供的mediaType并将字符集添加到其中.即使对于图片/jpeg,它也会发送
When I pass a String, it disregards the supplied mediaType and adds the charset to it. Even for image/jpeg it would send
image/jpeg; charset = utf-8
image/jpeg; charset=utf-8
到服务器.
使用byte []或File抑制该行为.
Using byte[] or File suppresses that behavior.
希望对您有帮助!
[愚蠢的我-为简单起见,我在测试过程中给了它一个String,因为我不在乎身体;-(]
[Stupid me - for simplicity I gave it a String during testing, as I didn't care about the body ;-( ]
这篇关于如何禁止将字符集自动添加到okhttp中的Content-Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!