user996505
user996505

Reputation: 1239

How to set Content-Type correctly?

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

Upvotes: 3

Views: 15016

Answers (2)

Steven Schlansker
Steven Schlansker

Reputation: 38526

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

Upvotes: 3

laz
laz

Reputation: 28638

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?

Upvotes: 3

Related Questions