What exactly does URLConnection.setDoOutput() affect?

sharptooth picture sharptooth · Dec 21, 2011 · Viewed 78.7k times · Source

There's setDoOutput() in URLConnection. According to documentation I should

Set the DoOutput flag to true if you intend to use the URL connection for output, false if not.

Now I'm facing exactly this problem - the Java runtime converts the request to POST once setDoOutput(true) is called and the server only responds to GET requests. I want to understand what happens if I remove that setDoOutput(true) from the code.

What exactly will this affect? Suppose I set it to false - what can I do now and what can't I do now? Will I be able to perform GET requests? What is "output" in context of this method?

Answer

Thilo picture Thilo · Dec 21, 2011

You need to set it to true if you want to send (output) a request body, for example with POST or PUT requests. With GET, you do not usually send a body, so you do not need it.

Sending the request body itself is done via the connection's output stream:

conn.getOutputStream().write(someBytes);