JAVA: httpclient 详解——第二章;

来源:互联网 发布:阿尔法拆单软件 编辑:程序博客网 时间:2024/06/05 09:49

相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  


 
链接  :  加上 http:    空格去掉
blog. csdn .net 
/lyc66666666666/article/details/36899463

相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  



链接  :  加上 http:    空格去掉

blog. csdn .net /lyc66666666666/article/details/36899463



相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  



链接  :  加上 http:    空格去掉

blog. csdn .net /lyc66666666666/article/details/36899463



相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  


http://blog.csdn.net/lyc66666666666/article/details/37902655




相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  





相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  


链接  :  加上 http:    空格去掉

blog. csdn .net /lyc66666666666/article/details/36899463




相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;


httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...


下面是测试代码(全部总结来自官方文档,以及翻译)


须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //=======================================第二章================================================  
  2.       
  3.     /** 
  4.      * 多线程并发访问服务器 
  5.      *  
  6.      * 每次http连接需要三次握手,开销很大,http/1.1默认支持连接复用; 
  7.      *  
  8.      * PoolingHttpClientConnectionManager 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 
  9.      *  
  10.      * 如下:setDefaultMaxPerRoute(3)之后,每次并发3个访问,所以打印输出是每次输出三个"test",验证了http连接管理器生效; 
  11.      *  
  12.      */  
  13.     private static void test9() throws InterruptedException,ExecutionException, IOException {  
  14.           
  15.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();  
  16.         connManager.setMaxTotal(200);//设置最大连接数200  
  17.         connManager.setDefaultMaxPerRoute(3);//设置每个路由默认连接数  
  18.         HttpHost host = new HttpHost("webservice.webxml.com.cn");//针对的主机  
  19.         connManager.setMaxPerRoute(new HttpRoute(host), 5);//每个路由器对每个服务器允许最大5个并发访问  
  20.           
  21.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();  
  22.           
  23.         String[] urisToGet = {   
  24.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  25.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  26.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  27.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  28.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  29.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  30.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  31.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",   
  32.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",  
  33.                 "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };  
  34.           
  35.         GetThread[] threads = new GetThread[urisToGet.length];  
  36.           
  37.         for (int i = 0; i < threads.length; i++) {  
  38.             HttpGet httpget = new HttpGet(urisToGet[i]);  
  39.             threads[i] = new GetThread(httpClient, httpget);  
  40.         }  
  41.           
  42.         for (int j = 0; j < threads.length; j++) {  
  43.             threads[j].start();  
  44.         }  
  45.           
  46.         for (int j = 0; j < threads.length; j++) {  
  47.             threads[j].join();  
  48.         }  
  49.                   
  50.                   
  51.     }  
  52.       
  53.     static class GetThread extends Thread {  
  54.         private final CloseableHttpClient httpClient;  
  55.         private final HttpContext context;  
  56.         private final HttpGet httpget;  
  57.   
  58.         public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {  
  59.             this.httpClient = httpClient;  
  60.             this.context = HttpClientContext.create();  
  61.             this.httpget = httpget;  
  62.         }  
  63.           
  64.         @Override  
  65.         public void run() {  
  66.             try {  
  67.                 CloseableHttpResponse response = httpClient.execute(httpget, context);  
  68.                 try {  
  69.                     HttpEntity entity = response.getEntity();  
  70.                     if(entity!=null){  
  71.                         System.out.println("test");  
  72.                     }  
  73.                 } finally {  
  74.                     response.close();  
  75.                 }  
  76.             } catch (ClientProtocolException ex) {  
  77.             } catch (IOException ex) {  
  78.             }  
  79.         }  
  80.     }  
  81.       
  82.       
  83.     /** 
  84.      *  清空失效连接: 
  85.      *  
  86.      *  连接的有效性检测是所有连接池都面临的一个通用问题,大部分HTTP服务器为了控制资源开销,并不会 
  87.         永久的维护一个长连接,而是一段时间就会关闭该连接。放回连接池的连接,如果在服务器端已经关闭,客 
  88.         户端是无法检测到这个状态变化而及时的关闭Socket的。这就造成了线程从连接池中获取的连接不一定是有效的。 
  89.         这个问题的一个解决方法就是在每次请求之前检查该连接是否已经存在了过长时间,可能已过期。 
  90.         但是这个方法会使得每次请求都增加额外的开销。HTTP Client4.0的HttpClientConnectionManager 提供了 
  91.         closeExpiredConnections()方法和closeIdleConnections()方法来解决该问题。 
  92.         前一个方法是清除连接池中所有过期的连接,至于连接什么时候过期可以设置,设置方法将在下面提到, 
  93.         而后一个方法则是关闭一定时间空闲的连接,可以使用一个单独的线程完成这个工作。 
  94.      */  
  95.     private static void test10(){  
  96.           
  97.         HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();  
  98.           
  99.         new IdleConnectionMonitorThread(manager).start();//启动线程,5秒钟清空一次失效连接  
  100.           
  101.         CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();  
  102.           
  103.         URI uri = null;//构建uri实体  
  104.         try {  
  105.             uri = new URIBuilder()  
  106.             .setScheme("http")  
  107.             .setHost("webservice.webxml.com.cn")  
  108.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  109.             .setParameter("""")  
  110.             .build();  
  111.         } catch (URISyntaxException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.         HttpPost post = new HttpPost(uri);  
  116.           
  117.         try {  
  118.             client.execute(post);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.     }  
  123.       
  124.     //这个线程负责使用连接管理器清空失效连接和过长连接  
  125.     private static class IdleConnectionMonitorThread extends Thread {  
  126.           
  127.         private final HttpClientConnectionManager connMgr;  
  128.         private volatile boolean shutdown;  
  129.           
  130.         public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
  131.             super();  
  132.             this.connMgr = connMgr;  
  133.         }  
  134.           
  135.         @Override  
  136.         public void run() {  
  137.             try {  
  138.                 while (!shutdown) {  
  139.                     synchronized (this) {  
  140.                         wait(5000);  
  141.                         System.out.println("清空失效连接...");  
  142.                         // 关闭失效连接  
  143.                         connMgr.closeExpiredConnections();  
  144.                         //关闭空闲超过30秒的连接  
  145.                         connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
  146.                     }  
  147.                 }  
  148.             } catch (InterruptedException ex) {  
  149.             }  
  150.         }  
  151.           
  152.         public void shutdown() {  
  153.             shutdown = true;  
  154.             synchronized (this) {  
  155.                 notifyAll();  
  156.             }  
  157.         }  
  158.     }  
  159.       
  160.       
  161.     /** 
  162.      *  
  163.      * http长连接策略: 
  164.      * 可以根据须要定制所须要的长连接策略,可根据服务器指定的超时时间,也可根据主机名自己指定超时时间; 
  165.      */  
  166.     private static void test11(){  
  167.           
  168.         //参考第一章的DefaultConnectionKeepAliveStrategy类  
  169.         ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {  
  170.             public long getKeepAliveDuration(HttpResponse response,HttpContext context) {  
  171.                 // 遍历response的header  
  172.                 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
  173.                   
  174.                 while (it.hasNext()) {  
  175.                     HeaderElement he = it.nextElement();  
  176.                     String param = he.getName();  
  177.                     String value = he.getValue();  
  178.                     if (value != null && param.equalsIgnoreCase("timeout")) {//如果头部包含timeout信息,则使用  
  179.                         try {  
  180.                             //超时时间设置为服务器指定的值  
  181.                             return Long.parseLong(value) * 1000;  
  182.                         } catch (NumberFormatException ignore) {  
  183.                         }  
  184.                     }  
  185.                 }  
  186.                 //获取主机  
  187.                 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);  
  188.                 if ("webservice.webxml.com.cn".equalsIgnoreCase(target.getHostName())) {  
  189.                     // 如果访问webservice.webxml.com.cn主机则设置长连接时间为5秒  
  190.                     return 51000;  
  191.                 } else {  
  192.                     // 其他为30秒  
  193.                     return 30 * 1000;  
  194.                 }  
  195.             }  
  196.         };  
  197.         CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();  
  198.           
  199.           
  200.         URI uri = null;//构建uri实体  
  201.         try {  
  202.             uri = new URIBuilder()  
  203.             .setScheme("http")  
  204.             .setHost("webservice.webxml.com.cn")  
  205.             .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")  
  206.             .setParameter("""")  
  207.             .build();  
  208.               
  209.         } catch (URISyntaxException e) {  
  210.             e.printStackTrace();  
  211.         }  
  212.           
  213.         HttpPost post = new HttpPost(uri);  
  214.           
  215.         try {  
  216.               
  217.             CloseableHttpResponse response =  client.execute(post);  
  218.             if(response.getStatusLine().getStatusCode()==200){  
  219.                 String result = EntityUtils.toString(response.getEntity());  
  220.                 System.out.println("返回的结果====="+result);  
  221.             }  
  222.               
  223.         } catch (ClientProtocolException e) {  
  224.             e.printStackTrace();  
  225.         } catch (IOException e) {  
  226.             e.printStackTrace();  
  227.         }  
  228.     }  
  229.       
  230.       
  231.       
  232.       
  233.     private static void test12() throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {  
  234.   
  235.         /** 
  236.          * Http连接使用java.net.Socket类来传输数据。这依赖于ConnectionSocketFactory接口来创建、初始化和连接socket。 
  237.          */  
  238.         HttpClientContext clientContext = HttpClientContext.create();  
  239.         PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();//Plain:简洁的  
  240.         Socket socket = sf.createSocket(clientContext);  
  241.         HttpHost target = new HttpHost("localhost");  
  242.         InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] { 127001}), 80);  
  243.         sf.connectSocket(1000, socket, target, remoteAddress, null,clientContext);  
  244.           
  245.   
  246.         //创建通用socket工厂  
  247.         ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();  
  248.           
  249.         //Creates default SSL context based on system properties(HttpClient没有自定义任何加密算法。它完全依赖于Java加密标准)  
  250.         SSLContext sslcontext = SSLContexts.createSystemDefault();  
  251.           
  252.         //创建ssl socket工厂  
  253.         LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  254.                 sslcontext,  
  255.                 SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);   
  256.           
  257.         //自定义的socket工厂类可以和指定的协议(Http、Https)联系起来,用来创建自定义的连接管理器。  
  258.         Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()    
  259.                 .register("http", plainsf)  
  260.                 .register("https", sslsf)  
  261.                 .build();  
  262.         HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);  
  263.         CloseableHttpClient client = HttpClients.  
  264.                 custom().  
  265.                 setConnectionManager(cm).  
  266.                 build();  
  267.           
  268.           
  269.         ////////////////////////////////////////////////////////////  
  270.         //自定义SSLContext  
  271. //      KeyStore myTrustStore = null;  
  272. //      SSLContext sslContext = SSLContexts.custom()  
  273. //              .useTLS()   //安全传输层协议(TLS)用于在两个通信应用程序之间提供保密性和数据完整性。该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。  
  274. //              .useSSL()  
  275. //              .loadTrustMaterial(myTrustStore)  
  276. //              .build();  
  277. //      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);  
  278.         ////////////////////////////////////////////////////////////////////  
  279.           
  280.           
  281.     }  
  282.       
  283.     /** 
  284.      * HttpClient代理服务器配置 
  285.      *  
  286.      * 使用代理服务器最简单的方式就是,指定一个默认的proxy参数。 
  287.      * 我们也可以让HttpClient去使用jre的代理服务器。 
  288.      * 又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。 
  289.      */  
  290.     private static void test13(){  
  291.           
  292.         //1、使用默认的代理  
  293.         HttpHost proxy = new HttpHost("8.8.8.8"8080);  
  294.         DefaultProxyRoutePlanner routePlanner1 = new DefaultProxyRoutePlanner(proxy);  
  295.         CloseableHttpClient httpclient1 = HttpClients.  
  296.                 custom()  
  297.                 .setRoutePlanner(routePlanner1)  
  298.                 .build();  
  299.           
  300.         //2、使用jre的代理  
  301.         SystemDefaultRoutePlanner routePlanner2 = new SystemDefaultRoutePlanner(ProxySelector.getDefault());  
  302.         CloseableHttpClient httpclient2 = HttpClients.  
  303.                 custom()  
  304.                 .setRoutePlanner(routePlanner2)  
  305.                 .build();  
  306.           
  307.           
  308.         //3、自定义代理  
  309.         HttpRoutePlanner routePlanner3 = new HttpRoutePlanner() {  
  310.                 public HttpRoute determineRoute(HttpHost target,HttpRequest request,HttpContext context) throws HttpException {  
  311.                       
  312.                     return new HttpRoute(  
  313.                             target,  
  314.                             null,  
  315.                             new HttpHost("8.8.8.8"8080),  
  316.                             "https".equalsIgnoreCase(target.getSchemeName())  
  317.                             );  
  318.                 }  
  319.             };  
  320.         CloseableHttpClient httpclient3 = HttpClients.  
  321.                 custom()  
  322.                 .setRoutePlanner(routePlanner3)  
  323.                 .build();  
  324.   
  325.     }  
  326.       
  327.       
  328.       



[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //Scheme类代表了一个协议模式,比如“http”或“https”同时包含一些协议属性,  
  2. 比如默认端口,用来为给定协议创建java.net.Socket实例的套接字工厂。  
  3. SchemeRegistry类用来维持一组Scheme,当去通过请求URI建立连接时,HttpClient可以从中选择:  
  4.   
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));  
  7.     sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);  
  8.     Scheme https = new Scheme("https", sf, 443);  
  9.     SchemeRegistry sr = new SchemeRegistry();  
  10.     sr.register(http);  
  11.     sr.register(https);  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //这里有一个从连接管理器中获取连接的示例:  
  2.   
  3.   
  4.     HttpParams params = new BasicHttpParams();  
  5.     Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);  
  6.     SchemeRegistry sr = new SchemeRegistry();  
  7.     sr.register(http);  
  8.     ClientConnectionManager connMrg = new SingleClientConnManager(params, sr);  
  9.     // 请求新连接。这可能是一个很长的过程。  
  10.     ClientConnectionRequest connRequest = connMrg.requestConnection(new HttpRoute(new HttpHost("localhost"80)), null);  
  11.     // 等待连接10秒  
  12.     ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);  
  13.     try {  
  14.     // 用连接在做有用的事情。当完成时释放连接。  
  15.     conn.releaseConnection();  
  16.     } catch (IOException ex) {  
  17.     // 在I/O error之上终止连接。  
  18.     conn.abortConnection();  
  19.     throw ex;  
  20.     }  

1 0
原创粉丝点击