多线程java应用程序中java.net.HttpURLConnection的不同实例

时间:2015-09-03 05:39:37

标签: java multithreading httpurlconnection

我有一个多线程的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());

1 个答案:

答案 0 :(得分:0)

因为你在HttpURLConnection上调用disconnect()而不是close()。

来自HttpURLConnection的JavaDoc(强调我的):

  

每个HttpURLConnection实例用于发出单个请求   与HTTP服务器的基础网络连接可能是   由其他实例透明地共享。调用close()方法   在一个HttpURLConnection的InputStream或OutputStream之后   请求可以释放与此实例关联的网络资源但是   对任何共享持久连接没有影响。 打电话给   如果持久化,disconnect()方法可能会关闭底层套接字   此时连接处于空闲状态。