java 如何正确设置 Content-Type?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7946294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Content-Type correctly?
提问by user996505
I want to change Content-Type but it dose not work...right? code:
我想更改 Content-Type 但它不起作用......对吗?代码:
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
System.out.println(conn.getContentType());
the output is not "text/plain; charset=utf-8"...anything wrong? Thanks
输出不是“text/plain; charset=utf-8”...有什么问题吗?谢谢
采纳答案by laz
The value of getContentType()
returns the value of the Content-Type
header from the response, not the value set on the request. See the Javadoc I linked to. What exactly are you trying to do?
的值从响应getContentType()
返回Content-Type
标头的值,而不是在请求上设置的值。请参阅我链接到的 Javadoc。你到底想做什么?
回答by Steven Schlansker
As laz correctly points out, setting Content-Type
on the outgoing request isn't going to control the Content-Type
you are going to get back on the response. If you have a server which is smart enough to dynamically control the Content-Type
the correct way to request a specific one is via an Accept header.
正如 laz 正确指出的那样,Content-Type
对传出请求的设置不会控制Content-Type
您将要返回的响应。如果您有一台足够智能的服务器,可以动态控制Content-Type
请求特定服务器的正确方式,那就是通过Accept 标头。
The Accept request-header field can be used to specify certain media types which are acceptable for the response. The example
Accept: audio/*; q=0.2, audio/basic
SHOULD be interpreted as "I prefer audio/basic, but send me any audio type if it is the best available after an 80% mark-down in quality."
Accept 请求头字段可用于指定响应可接受的某些媒体类型。这个例子
Accept: audio/*; q=0.2, audio/basic
应该被解释为“我更喜欢音频/基本,但如果在质量下降 80% 后它是最好的,请给我发送任何音频类型。”