java HttpURLConnection.getInputStream() 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10705240/
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
HttpURLConnection.getInputStream() blocks
提问by Sandman
I'm using the HttpURLConnection class to make http requests. My code looks something like this-
我正在使用 HttpURLConnection 类来发出 http 请求。我的代码看起来像这样 -
while(true){
try{
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(2*1000);
InputStream in=connection.getInputStream();
}
catch(SocketTimeOutException e){}
catch(IOException e){}
}
I do some processing on the data once I retrieve the InputStream object. My problem is that if I let the program run long enough, the call to getInputStream blocks and I never get past that.
Am I missing something? Any pointers or help would be greatly appreciated. Thanks.
一旦我检索到 InputStream 对象,我就会对数据进行一些处理。我的问题是,如果我让程序运行足够长的时间,对 getInputStream 的调用就会阻塞,而且我永远不会超过它。
我错过了什么吗?任何指示或帮助将不胜感激。谢谢。
采纳答案by Zaki
Set the read time out for the connection. Also, close the streams in a finally block once you're done with them.
设置连接的读取超时。此外,完成后在 finally 块中关闭流。
回答by Nurlan
You should close connections that are not used. Here is example:
您应该关闭未使用的连接。这是示例:
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(2*1000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
reader.close();