java – 多线程httpClient

public class test {
    public static final int nThreads = 2;

    public static void main(String[] args) throws ExecutionException, InterruptedException{
    //  Runnable myrunnable = new myRunnable();
        ExecutorService execute = Executors.newFixedThreadPool(nThreads);

        for (int i = 0; i < nThreads; ++i) {
            execute.execute(new MyTask());
        }           

        execute.awaitTermination(1000, TimeUnit.MILLISECONDS);

        execute.shutdown();
    }
}

class MyTask implements Runnable {
    public static final int maxCalls = 10;
    public static final int sleepMillis = 500;
    private static HttpResponse response;
    private static HttpClient httpclient;

    public void run(){
        int counter = 0;

        while (true) {

            if (counter >= maxCalls) {
                break;
            }
            try {
                Thread.currentThread().sleep(sleepMillis);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            execHttpRequest();

            ++counter;
        }
    }

    private void execHttpRequest() {
        httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("My URL");

        try {

            response = httpclient.execute(httpget);
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String output;
            while((output=br.readLine())!=null){
                System.out.println(Thread.currentThread().getName() +output);
            }
            br.close();

            httpclient.getConnectionManager().shutdown();
            //httpclient.getConnectionManager().shutdown();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{

            httpclient.getConnectionManager().shutdown();
        }

    }


}

运行此代码时,我得到以下异常:

Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
    at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:216)
    at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:190)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:401)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at MyTask.execHttpRequest(test.java:72)
    at MyTask.run(test.java:60)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
java.io.InterruptedIOException: Connection has been shut down
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:543)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at MyTask.execHttpRequest(test.java:72)
    at MyTask.run(test.java:60)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.apache.http.impl.conn.ConnectionShutdownException
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.assertValid(AbstractPooledConnAdapter.java:86)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.getRoute(AbstractPooledConnAdapter.java:112)
    at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:740)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:577)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
    ... 8 more

当我执行http请求时,我会看到这些异常.它适用于单线程.我试图调用一个特定的URL(它工作得很好)但是当我向它添加多个线程时,它会抛出一个非法的状态异常.

您需要定义多线程HttpConnectionManager,例如
MultiThreadedHttpConnectionManager connectionManager = 
                                  new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(connectionManager);

有关详细信息,请参阅 http://hc.apache.org/httpclient-3.x/threading.html

翻译自:https://stackoverflow.com/questions/8138128/multi-threading-httpclient

原文 

https://codeday.me/bug/20190113/526789.html

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » java – 多线程httpClient

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址