What exactly does URLConnection.setDoOutput() affect?

时光毁灭记忆、已成空白 提交于 2019-11-26 20:02:12

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);

setDoOutput(true) is used for POST and PUT requests. If it is false then it is for using GET requests.

Adding a comment, if you have a long lasting connection and you send both GETs and POSTs, this is what I do:

if (doGet) {    // some boolean
    con.setDoOutput(false); // reset any previous setting, if con is long lasting
    con.setRequestMethod("GET");
}
else {
    con.setDoOutput(true);  // reset any previous setting, if con is long lasting
    con.setRequestMethod("POST");
}

And to avoid making the connection long lasting, close it each time.

if (doClose)    // some boolean
    con.setRequestProperty("Connection", "close");

con.connect();              // force connect request
public void setDoOutput( boolean dooutput )

It takes a value as the parameter and sets this value of the doOutput field for this URLConnection to the specified value.

A URL connection can be used for input and/or output. Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!