SetDoOutput()到底会影响什么?

URLConnection里有 setDoOutput()根据 文件我应该

如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true,如果不设置,则设置为 false。

现在我面对的是 正是这个问题—— Java 运行时在调用 setDoOutput(true)时将请求转换为 POST,而服务器只响应 GET请求。我想知道如果从代码中删除 setDoOutput(true)会发生什么。

这究竟会影响到什么?假设我把它设置为 false-我现在能做什么,不能做什么?我能够执行 GET请求吗?在这个方法的上下文中,什么是“输出”?

89547 次浏览

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

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.

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

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