Java 使用 HttpURLConnection 时出现“非法状态异常:已连接”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29906562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Illegal State Exception: Already Connected" when using HttpURLConnection
提问by arpitpanwar
I get an illegal state exception when i set DoOutput to true.
当我将 DoOutput 设置为 true 时,出现非法状态异常。
public boolean sendLinksToMaster(String ipport, List<String> links){
boolean sent = false;
String[] tokens = ipport.split(":");
String data = edu.cis555.searchengine.utils.Utils.generateLinks(links);
HttpURLConnection conn=null;
try{
String encodedData = URLEncoder.encode(data, "UTF-8");
try{
String ip =tokens[0];
String port = tokens[1];
String path = edu.cis555.searchengine.utils.Constants.URL_ADD_LINK;
System.setProperty("http.keepAlive", "false");
URL u = new URL("http", ip, Integer.parseInt(port),"/"+path);
conn = (HttpURLConnection)u.openConnection();
//ERROR IN THIS LINE
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream stream = conn.getOutputStream();
stream.write(encodedData.getBytes());
stream.close();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK)
sent=true;
// LOG.debug(conn.getResponseCode());
conn.disconnect();
}catch(MalformedURLException mfe){
LOG.debug(mfe.getMessage());
if(conn!=null){
conn.disconnect();
}
}catch(IOException ioe){
LOG.debug(ioe.getMessage());
if(conn!=null){
conn.disconnect();
}
}
}catch(Exception e){
LOG.debug(e.getMessage());
if(conn!=null){
conn.disconnect();
}
}
return sent;
}
The stack trace displayed for the same is:
显示的堆栈跟踪是:
java.lang.IllegalStateException: Already connected
at java.net.URLConnection.setDoOutput(Unknown Source)
at edu.upenn.cis455.xpathengine.utils.pool.ThreadPool.sendLinksToMaster(ThreadPool.java:357)
at edu.upenn.cis455.xpathengine.utils.pool.ThreadPool$Worker.processAndAddToQueue(ThreadPool.java:314)
at edu.upenn.cis455.xpathengine.utils.pool.ThreadPool$Worker.run(ThreadPool.java:269)
at java.lang.Thread.run(Unknown Source)
I don't see anything I am doing wrong with sending the request. Could anyone point out what is missing or what am I doing wrong
我在发送请求时没有发现我做错了什么。谁能指出缺少什么或我做错了什么
采纳答案by Sharcoux
I got the same problem and solved it. In my case, it was caused because I had a forgotten watch for connection.getResponseCode()
in my debugging interface in NetBeans. Hope it might help others making the same mistake.
我遇到了同样的问题并解决了它。就我而言,这是因为我connection.getResponseCode()
在 NetBeans 的调试界面中忘记了监视。希望它可以帮助其他犯同样错误的人。
If you have any watch relative to the response value of the request, such as getResponseCode()
, getResponseMessage()
, getInputStream()
or even just connect()
, you will get this error in debugging mode.
如果您有任何与请求的响应值相关的监视,例如getResponseCode()
, getResponseMessage()
,getInputStream()
甚至只是connect()
,您将在调试模式下收到此错误。
All of the previous methods implicitly call connect()
and fire the request. So when you reach setDoOutput
, the connection is already made.
前面的所有方法都隐式调用connect()
并触发请求。所以当你到达时setDoOutput
,连接已经建立。
回答by Alaa Abuzaghleh
put the stream.close(); in finally block
把 stream.close(); 在 finally 块中
回答by sawa we
sometimes it is as easy as make sure you do not have http in stead of https.
有时它就像确保你没有 http 而不是 https 一样简单。
回答by Rahul jha
Apart from the watches as mentioned in the previous comment, it might also occur if there is something wrong with the connection. For example:
除了前面评论中提到的手表,如果连接有问题,也可能会发生。例如:
I was setting a property:post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>")
after writing into OutPut Stream like post.getOutputStream().write(jsonBody.getBytes("UTF-8"));
我正在设置一个属性:post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>")
在写入 OutPut Stream 之后post.getOutputStream().write(jsonBody.getBytes("UTF-8"));
It was like:
它就像:
post.getOutputStream().write(jsonBody.getBytes("UTF-8"))
post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>")
In this case, I was also getting "Already Connected". To fix it I made it like:
在这种情况下,我也收到了“已经连接”的信息。为了修复它,我使它像:
post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>")
post.getOutputStream().write(jsonBody.getBytes("UTF-8"))