使用MultiThreadedHttpConnectionManager为同一httpclient设置不同的套接字超时

时间:2011-11-28 20:59:42

标签: java multithreading apache-commons-httpclient

我有两个线程使用相同的HTTPClientTest实例。两个线程在同一个HTTPClientTest上调用send方法。我应该如何为每个调用send方法的线程设置不同的套接字超时。如果我在send方法中执行类似的操作,那么执行send方法的两个线程将具有相同的套接字超时 managerParams.setSoTimeout(60); connectionManager.setParams(managerParams);

如何为在同一个HTTPClientTest实例上执行send方法的多个线程创建不同的套接字超时。

public class HTTPClientTest implements Runnable{
private HttpClient httpClient;
private MultiThreadedHttpConnectionManager connectionManager;
private HttpConnectionManagerParams managerParams;
private HttpClientTest()
{
     connectionManager = new MultiThreadedHttpConnectionManager();
     httpClient = new HttpClient(connectionManager);
}
public static synchronized HTTPClientTest getInstance()
{
    if(instance == null)
        instance = new HTTPClientTest();
    return instance;
}

public void send(String message, String url)
{
    PostMethod post = new PostMethod(url);
    String reply = "";
    String length = message.length() + "";
    post.setRequestHeader("Content-Length", length);
    try 
    {
        System.out.println("HTTP request: " + message);
        StringRequestEntity postBody = new StringRequestEntity(message, "text/xml", "UTF-8");
        post.setRequestEntity(postBody);
        int status = httpClient.executeMethod(post);
        System.out.println("HTTP status: " + status);
        reply = post.getResponseBodyAsString();
        System.out.println("HTTP Post response code: " + reply);

    } 
    catch(HttpException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        post.releaseConnection();
    }

}
}

1 个答案:

答案 0 :(得分:1)

很简单:

get.getParams().setParameter("http.socket.timeout",20000);
httpclient.execute(get);

线程不共享mothods,是吗? 根据需要进行修改。