Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Content-Type correctly?

Tags:

java

http

I want to change Content-Type but it dose not work...right? code:

  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

like image 963
user996505 Avatar asked Nov 26 '25 13:11

user996505


2 Answers

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?

like image 145
laz Avatar answered Nov 29 '25 03:11

laz


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.

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."

like image 23
Steven Schlansker Avatar answered Nov 29 '25 02:11

Steven Schlansker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!