Dis*_*tum 6 java httpurlconnection
我正在HttpURLConnection客户端使用在HTTP流(服务器推送)情况下使用响应.虽然服务器可以通过关闭响应来关闭连接,但客户端也需要能够执行此操作.
客户端InputStream在单独的线程中处理,如下所示:
@Override
public void run() {
try {
for (int b = in.read(); b >= 0; b = in.read()) {
char c = (char) b;
// Do something with the character
// ...
}
}
catch (IOException e) {
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我HttpURLConnection.disconnect()从发起连接的线程调用时(重要的信息是它与处理输入的线程不同),该调用无限期挂起.我甚至把它留在了一夜之间它仍然悬挂着.甚至打电话都Thread.interrupt()没有帮助.
建议?
如果没有更改读取线程进行轮询使用,InputStream.available()并且在没有可用字节的情况下睡眠短暂的perdiod ,看起来无法完成此操作,同时检查一些标志以查看线程是否应该结束.
解决方案是仅使用Apache HTTP组件.通过将GET请求的代码封装在一个类中,可以很容易地将其集成到现有代码中.
public class HttpGetConnection implements AutoCloseable {
public HttpGetConnection(String url) throws IOException {
client = new DefaultHttpClient();
get = new HttpGet(url);
response = client.execute(get);
entity = response.getEntity();
}
public InputStream getContent() throws IOException {
content = entity.getContent();
return content;
}
@Override
public void close() throws Exception {
get.abort();
try {
content.close();
}
catch (IOException e) {
}
}
private HttpClient client;
private HttpGet get;
private HttpResponse response;
private HttpEntity entity;
private InputStream content;
}
Run Code Online (Sandbox Code Playgroud)
原始帖子中的循环可以保持原样,并且在调用后不久读取线程将会死亡HttpGetConnection.close().
| 归档时间: |
|
| 查看次数: |
8521 次 |
| 最近记录: |