Subversion Repositories javautils

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * ====================================================================
  3.  *
  4.  *  Licensed to the Apache Software Foundation (ASF) under one or more
  5.  *  contributor license agreements.  See the NOTICE file distributed with
  6.  *  this work for additional information regarding copyright ownership.
  7.  *  The ASF licenses this file to You under the Apache License, Version 2.0
  8.  *  (the "License"); you may not use this file except in compliance with
  9.  *  the License.  You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  *  Unless required by applicable law or agreed to in writing, software
  14.  *  distributed under the License is distributed on an "AS IS" BASIS,
  15.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  *  See the License for the specific language governing permissions and
  17.  *  limitations under the License.
  18.  * ====================================================================
  19.  *
  20.  * This software consists of voluntary contributions made by many
  21.  * individuals on behalf of the Apache Software Foundation.  For more
  22.  * information on the Apache Software Foundation, please see
  23.  * <http://www.apache.org/>.
  24.  *
  25.  */
  26.  
  27. package org.apache.http.examples.client;
  28.  
  29. import org.apache.http.HttpEntity;
  30. import org.apache.http.HttpResponse;
  31. import org.apache.http.HttpVersion;
  32. import org.apache.http.client.HttpClient;
  33. import org.apache.http.client.methods.HttpGet;
  34. import org.apache.http.conn.ClientConnectionManager;
  35. import org.apache.http.conn.params.ConnManagerParams;
  36. import org.apache.http.conn.scheme.PlainSocketFactory;
  37. import org.apache.http.conn.scheme.Scheme;
  38. import org.apache.http.conn.scheme.SchemeRegistry;
  39. import org.apache.http.impl.client.DefaultHttpClient;
  40. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  41. import org.apache.http.params.BasicHttpParams;
  42. import org.apache.http.params.HttpParams;
  43. import org.apache.http.params.HttpProtocolParams;
  44. import org.apache.http.protocol.HttpContext;
  45. import org.apache.http.protocol.BasicHttpContext;
  46. import org.apache.http.util.EntityUtils;
  47.  
  48. /**
  49.  * An example that performs GETs from multiple threads.
  50.  *
  51.  */
  52. public class ClientMultiThreadedExecution {
  53.  
  54.     public static void main(String[] args) throws Exception {
  55.         // Create and initialize HTTP parameters
  56.         HttpParams params = new BasicHttpParams();
  57.         ConnManagerParams.setMaxTotalConnections(params, 100);
  58.         HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  59.        
  60.         // Create and initialize scheme registry
  61.         SchemeRegistry schemeRegistry = new SchemeRegistry();
  62.         schemeRegistry.register(
  63.                 new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  64.        
  65.         // Create an HttpClient with the ThreadSafeClientConnManager.
  66.         // This connection manager must be used if more than one thread will
  67.         // be using the HttpClient.
  68.         ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
  69.         HttpClient httpClient = new DefaultHttpClient(cm, params);
  70.        
  71.         // create an array of URIs to perform GETs on
  72.         String[] urisToGet = {
  73.             "http://hc.apache.org/",
  74.             "http://hc.apache.org/httpcomponents-core/",
  75.             "http://hc.apache.org/httpcomponents-client/",
  76.             "http://svn.apache.org/viewvc/httpcomponents/"
  77.         };
  78.        
  79.         // create a thread for each URI
  80.         GetThread[] threads = new GetThread[urisToGet.length];
  81.         for (int i = 0; i < threads.length; i++) {
  82.             HttpGet httpget = new HttpGet(urisToGet[i]);
  83.             threads[i] = new GetThread(httpClient, httpget, i + 1);
  84.         }
  85.        
  86.         // start the threads
  87.         for (int j = 0; j < threads.length; j++) {
  88.             threads[j].start();
  89.         }
  90.        
  91.         // join the threads
  92.         for (int j = 0; j < threads.length; j++) {
  93.             threads[j].join();
  94.         }
  95.  
  96.         // When HttpClient instance is no longer needed,
  97.         // shut down the connection manager to ensure
  98.         // immediate deallocation of all system resources
  99.         httpClient.getConnectionManager().shutdown();        
  100.     }
  101.    
  102.     /**
  103.      * A thread that performs a GET.
  104.      */
  105.     static class GetThread extends Thread {
  106.        
  107.         private final HttpClient httpClient;
  108.         private final HttpContext context;
  109.         private final HttpGet httpget;
  110.         private final int id;
  111.        
  112.         public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
  113.             this.httpClient = httpClient;
  114.             this.context = new BasicHttpContext();
  115.             this.httpget = httpget;
  116.             this.id = id;
  117.         }
  118.        
  119.         /**
  120.          * Executes the GetMethod and prints some status information.
  121.          */
  122.         @Override
  123.         public void run() {
  124.            
  125.             System.out.println(id + " - about to get something from " + httpget.getURI());
  126.  
  127.             try {
  128.                
  129.                 // execute the method
  130.                 HttpResponse response = httpClient.execute(httpget, context);
  131.                
  132.                 System.out.println(id + " - get executed");
  133.                 // get the response body as an array of bytes
  134.                 HttpEntity entity = response.getEntity();
  135.                 if (entity != null) {
  136.                     byte[] bytes = EntityUtils.toByteArray(entity);
  137.                     System.out.println(id + " - " + bytes.length + " bytes read");
  138.                 }
  139.                
  140.             } catch (Exception e) {
  141.                 httpget.abort();
  142.                 System.out.println(id + " - error: " + e);
  143.             }
  144.         }
  145.        
  146.     }
  147.    
  148. }
  149.