[英]Different instance of java.net.HttpURLConnection in multithreaded java application
我有一个多线程的Java客户端,它将数据发布到服务器并使用HttpURLConnection
读取响应。 客户端的每个实例都是线程,它们不共享任何东西,即使不共享HttpURLConnection
。 (每个线程都有自己的HttpURLConnection
),而且似乎仍然不是线程安全的。 任何人都可以确认这种行为,您对此有何建议? 顺便说一句,我已经看到了类似的问题,但是那是在不同线程之间共享HttpURLConnection
。 请注意,就我而言,它不是共享的。
public class ESIHttpCaller{
private final String ESIHTTPURL = "http://localhost:7033/FBWS/eigBagHttpDispatcher"
private HttpURLConnection connection = null;
protected StringBuilder response = new StringBuilder();
public CBBag executePost(byte[] input) throws CBException {
InputStream is = null;
DataOutputStream wr =null;
int STATE = 0;
try{
// Create connection
URL url = new URL(getConnectionUrl());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset="+encoding);
connection.setRequestProperty("Content-Length", "" + Integer.toString(length));
connection.setRequestProperty("encoding", encoding);
connection.setRequestProperty("Accept-Encoding", encoding);
connection.setConnectTimeout(getConnectTimeout());
connection.setReadTimeout(getReadTimeout());
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
wr = new DataOutputStream(connection.getOutputStream());
wr.write(input);
wr.flush();
//Get response
STATE = 1;
is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is,encoding));
String line = rd.readLine() ;
while (line != null ) {
response.append(line);
line = rd.readLine();
}
rd.close();
return handleResponse(response);
}
catch (Exception e) {
closeQuietly(is,wr);
throw handleException(STATE, e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
线程中的调用方代码如下:
ESIHttpCaller caller = new ESIHttpCaller();
caller.setTcid(tcid);
return caller.executePost(outStr.getBytes());
因为您在HttpURLConnection上调用了connect()而不是close()。
从HttpURLConnection的JavaDoc(重点是我的):
每个HttpURLConnection实例用于发出单个请求,但与HTTP服务器的基础网络连接可以由其他实例透明共享 。 请求后在HttpURLConnection的InputStream或OutputStream上调用close()方法可能会释放与此实例关联的网络资源,但对任何共享的持久连接都没有影响。 如果持久连接当时处于空闲状态,则调用disconnect()方法可能会关闭基础套接字 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.