How to remove header from URLConnection

I am referring to a file download service that accepts post data rather than generating data. By default, java HttpURLConnection sets the Content-Type header to application/x-www-form-urlencoded . this is clearly wrong if I send clean data.

i (the client) does not know the type of content, so I do not want the Content-Type header to be set at all. the service has a function in which it will guess the type of content (based on the file name, reading some data from the file, etc.).

how to disable the header? there is no removal of the header, and setting it to null does not change the value and does not set it to an empty string, as a result of which the header will not be set.

+7
source share
4 answers

Use Apache HttpClient instead of URLConnection

Use the free Request to generate your request.

use removeHeader ()

+1
source

I have not tested this approach, but you can try the following:

Extend HttpURLConnection and try to override the getContentHandler () and setContentHandler (...) methods. Most likely, this should work the way you look at the getContentHandler () code.

+1
source

What does it mean "I don't want the Content-Type header to set at all"?

The browser (or another http client) sends your mail request to the server, so it must tell the server how it encoded the parameters.

If the Content-Type header is not set, on the server side you (= your server) will not be able to figure out how to parse the received data.

If you did not set Content-Type, the default value will be used.

Your browser (or another http client) MUST do two things:

  • Send key / value pairs.
  • Tell the server how key / value pairs were encoded.

Thus, it is impossible to completely get rid of this header.

0
source

I just accomplished this by setting the header to null.

 connection.setRequestProperty(MY_HEADER, null); 
0
source

All Articles