HttpURLConnection:java.lang.IllegalStateException:已连接 [英] HttpURLConnection: java.lang.IllegalStateException: Already connected
问题描述
我正在尝试使用HttpURLClient使用下面显示的HttpRestClient
类将一些POST数据发送到服务器.执行时
I'm trying to use HttpURLClient to send some POST data to a server using the HttpRestClient
class shown below. When executing
conn.setDoInput(true);
我知道
java.lang.IllegalStateException: Already connected
我卸载了该应用程序,仍然出现相同的错误.
I uninstalled the app, and still get the same error.
在所有示例中,我都看到openConnection在setDoInput
之前被调用.如果顾名思义,openConnection
打开一个连接,则永远不要在setDoInput之前使用它,对吗?我想念什么?
In all the example I've seen openConnection is called before setDoInput
. If, as its name suggests, openConnection
opens a connection, it should never be used before `setDoInput, right? What am I missing?
也许在执行disconnect
之前它崩溃了.那可能是原因吗?如果是这样,如何断开旧连接?
Maybe at some point it crashed before executing disconnect
. Could that be the reason? If so, how can I disconnect the old connection?
public class HttpRestClient {
static public int post(String urlStr, List<NameValuePair> data){
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(data));
writer.flush();
writer.close();
os.close();
InputStream is = conn.getInputStream();
String dude = readIt(is);
return 1;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
finally {
if(conn!=null) conn.disconnect();
}
}
}
推荐答案
这可能是由于在IDE中进行调试时需要监视.请参阅此答案. 它发生在我身上,很难发现.
This might be due to watches while debugging in your IDE. See this answer. It happened to me and was hard to discover.
这篇关于HttpURLConnection:java.lang.IllegalStateException:已连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!