HttpClient实现同步(sync)和异步(Async)

pom:

 

4.5

4.1

        
            org.projectlombok
            lombok
            ${lombok.version}
        


        
            org.apache.httpcomponents
            httpasyncclient
            ${http-async-client.version}
        


        
        
            org.apache.httpcomponents
            httpclient
            ${httpclient.version}
        


        
            org.apache.httpcomponents
            httpmime
            ${httpclient.version}
        
    


 


        
            org.projectlombok
            lombok
            ${lombok.version}
        

        
            org.apache.httpcomponents
            httpasyncclient
            ${http-async-client.version}
        

        
        
            org.apache.httpcomponents
            httpclient
            ${httpclient.version}
        

        
            org.apache.httpcomponents
            httpmime
            ${httpclient.version}
        
    

java:async

[java] view plain copy print ?
  1. package com.xxx.emidas.monitor.api.util;  
  2.   
  3. import org.apache.http.*;  
  4. import org.apache.http.client.CookieStore;  
  5. import org.apache.http.client.config.AuthSchemes;  
  6. import org.apache.http.client.config.CookieSpecs;  
  7. import org.apache.http.client.config.RequestConfig;  
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  9. import org.apache.http.client.methods.CloseableHttpResponse;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.client.protocol.HttpClientContext;  
  13. import org.apache.http.concurrent.FutureCallback;  
  14. import org.apache.http.config.Registry;  
  15. import org.apache.http.config.RegistryBuilder;  
  16. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  17. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  18. import org.apache.http.conn.ssl.NoopHostnameVerifier;  
  19. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  20. import org.apache.http.impl.client.*;  
  21. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  22. import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;  
  23. import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;  
  24. import org.apache.http.impl.nio.client.HttpAsyncClients;  
  25. import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;  
  26. import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;  
  27. import org.apache.http.util.EntityUtils;  
  28.   
  29. import javax.net.ssl.SSLContext;  
  30. import javax.net.ssl.TrustManager;  
  31. import javax.net.ssl.X509TrustManager;  
  32. import java.io.IOException;  
  33. import java.io.InputStream;  
  34. import java.io.InputStreamReader;  
  35. import java.io.Reader;  
  36. import java.security.KeyManagementException;  
  37. import java.security.NoSuchAlgorithmException;  
  38. import java.security.cert.CertificateException;  
  39. import java.security.cert.X509Certificate;  
  40. import java.util.ArrayList;  
  41. import java.util.Arrays;  
  42. import java.util.List;  
  43. import java.util.concurrent.Future;  
  44.   
  45. /** 
  46.  * Created by Administrator on 2015/11/28. 
  47.  */  
  48. public class HttpAsyncClientUtil {  
  49.     private static HttpClientContext context = HttpClientContext.create();  
  50.   
  51.     /** 
  52.      * http async get 
  53.      * 
  54.      * @param url 
  55.      * @param data 
  56.      * @return 
  57.      */  
  58.     public static void doGet(String url, String data) {  
  59.         CookieStore cookieStore = new BasicCookieStore();  
  60.         final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();  
  61.   
  62.         httpClient.start();  
  63.         HttpGet httpGet = new HttpGet(url);  
  64.         //httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");  
  65.         try {  
  66.             httpClient.execute(httpGet, context, new FutureCallback() {  
  67.                 @Override  
  68.                 public void completed(HttpResponse result) {  
  69.                     String body="";  
  70.                     //这里使用EntityUtils.toString()方式时会大概率报错,原因:未接受完毕,链接已关  
  71.                     try {  
  72.                         HttpEntity entity = result.getEntity();  
  73.                         if (entity != null) {  
  74.                             final InputStream instream = entity.getContent();  
  75.                             try {  
  76.                                 final StringBuilder sb = new StringBuilder();  
  77.                                 final char[] tmp = new char[1024];  
  78.                                 final Reader reader = new InputStreamReader(instream,"UTF-8");  
  79.                                 int l;  
  80.                                 while ((l = reader.read(tmp)) != -1) {  
  81.                                     sb.append(tmp, 0, l);  
  82.                                 }  
  83.                                 body = sb.toString();  
  84.                                 System.out.println(body);  
  85.                             } finally {  
  86.                                 instream.close();  
  87.                                 EntityUtils.consume(entity);  
  88.                             }  
  89.                         }  
  90.                     } catch (ParseException e) {  
  91.                         e.printStackTrace();  
  92.                     }catch (IOException e) {  
  93.                         e.printStackTrace();  
  94.                     }finally {  
  95.                         close(httpClient);  
  96.                     }  
  97.                 }  
  98.   
  99.                 @Override  
  100.                 public void failed(Exception ex) {  
  101.                     System.out.println(ex.toString());  
  102.                     close(httpClient);  
  103.                 }  
  104.   
  105.                 @Override  
  106.                 public void cancelled() {  
  107.   
  108.                 }  
  109.             });  
  110.         } catch (Exception e) {  
  111.         }  
  112.   
  113.         System.out.println("end-----------------------");  
  114.     }  
  115.   
  116.     /** 
  117.      * http async post 
  118.      * 
  119.      * @param url 
  120.      * @param values 
  121.      * @return 
  122.      */  
  123.     public static void doPost(String url, List values) {  
  124.         CookieStore cookieStore = new BasicCookieStore();  
  125.         CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();  
  126.   
  127.         HttpPost httpPost = new HttpPost(url);  
  128.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  129.         httpPost.setEntity(entity);  
  130.         try {  
  131.             httpClient.execute(httpPost, context, new FutureCallback() {  
  132.                 @Override  
  133.                 public void completed(HttpResponse result) {  
  134.                     System.out.println(result.toString());  
  135.                 }  
  136.   
  137.                 @Override  
  138.                 public void failed(Exception ex) {  
  139.                     System.out.println(ex.toString());  
  140.                 }  
  141.   
  142.                 @Override  
  143.                 public void cancelled() {  
  144.   
  145.                 }  
  146.             });  
  147.         } catch (Exception e) {  
  148.         }  
  149.     }  
  150.   
  151.     private static void close(CloseableHttpAsyncClient client) {  
  152.         try {  
  153.             client.close();  
  154.         } catch (IOException e) {  
  155.             e.printStackTrace();  
  156.         }  
  157.     }  
  158.   
  159.     /** 
  160.      * 直接把Response内的Entity内容转换成String 
  161.      * 
  162.      * @param httpResponse 
  163.      * @return 
  164.      */  
  165.     public static String toString(CloseableHttpResponse httpResponse) {  
  166.         // 获取响应消息实体  
  167.         String result = null;  
  168.         try {  
  169.             HttpEntity entity = httpResponse.getEntity();  
  170.             if (entity != null) {  
  171.                 result = EntityUtils.toString(entity, "UTF-8");  
  172.             }  
  173.         } catch (Exception e) {  
  174.         } finally {  
  175.             try {  
  176.                 httpResponse.close();  
  177.             } catch (IOException e) {  
  178.                 e.printStackTrace();  
  179.             }  
  180.         }  
  181.         return result;  
  182.     }  
  183.   
  184.   
  185.     public static void main(String[] args) throws Exception{  
  186.         CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();  
  187.         try {  
  188.             httpclient.start();  
  189.             HttpGet request = new HttpGet("http://www.apache.org/");  
  190.             Future future = httpclient.execute(request, null);  
  191.             HttpResponse response = future.get();  
  192.             System.out.println("Response: " + response.getStatusLine());  
  193.             System.out.println("Shutting down");  
  194.         } finally {  
  195.             httpclient.close();  
  196.         }  
  197.         System.out.println("Done");  
  198.     }  
  199. }  
package com.xxx.emidas.monitor.api.util;

import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * Created by Administrator on 2015/11/28.
 */
public class HttpAsyncClientUtil {
    private static HttpClientContext context = HttpClientContext.create();

    /**
     * http async get
     *
     * @param url
     * @param data
     * @return
     */
    public static void doGet(String url, String data) {
        CookieStore cookieStore = new BasicCookieStore();
        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

        httpClient.start();
        HttpGet httpGet = new HttpGet(url);
        //httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            httpClient.execute(httpGet, context, new FutureCallback() {
                @Override
                public void completed(HttpResponse result) {
                    String body="";
                    //这里使用EntityUtils.toString()方式时会大概率报错,原因:未接受完毕,链接已关
                    try {
                        HttpEntity entity = result.getEntity();
                        if (entity != null) {
                            final InputStream instream = entity.getContent();
                            try {
                                final StringBuilder sb = new StringBuilder();
                                final char[] tmp = new char[1024];
                                final Reader reader = new InputStreamReader(instream,"UTF-8");
                                int l;
                                while ((l = reader.read(tmp)) != -1) {
                                    sb.append(tmp, 0, l);
                                }
                                body = sb.toString();
                                System.out.println(body);
                            } finally {
                                instream.close();
                                EntityUtils.consume(entity);
                            }
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        close(httpClient);
                    }
                }

                @Override
                public void failed(Exception ex) {
                    System.out.println(ex.toString());
                    close(httpClient);
                }

                @Override
                public void cancelled() {

                }
            });
        } catch (Exception e) {
        }

        System.out.println("end-----------------------");
    }

    /**
     * http async post
     *
     * @param url
     * @param values
     * @return
     */
    public static void doPost(String url, List values) {
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
        httpPost.setEntity(entity);
        try {
            httpClient.execute(httpPost, context, new FutureCallback() {
                @Override
                public void completed(HttpResponse result) {
                    System.out.println(result.toString());
                }

                @Override
                public void failed(Exception ex) {
                    System.out.println(ex.toString());
                }

                @Override
                public void cancelled() {

                }
            });
        } catch (Exception e) {
        }
    }

    private static void close(CloseableHttpAsyncClient client) {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 直接把Response内的Entity内容转换成String
     *
     * @param httpResponse
     * @return
     */
    public static String toString(CloseableHttpResponse httpResponse) {
        // 获取响应消息实体
        String result = null;
        try {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static void main(String[] args) throws Exception{
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        try {
            httpclient.start();
            HttpGet request = new HttpGet("http://www.apache.org/");
            Future future = httpclient.execute(request, null);
            HttpResponse response = future.get();
            System.out.println("Response: " + response.getStatusLine());
            System.out.println("Shutting down");
        } finally {
            httpclient.close();
        }
        System.out.println("Done");
    }
}

java normal:

[java] view plain copy print ?
  1. package com.xxx.emidas.monitor.api.util;  
  2.   
  3. import org.apache.http.Consts;  
  4. import org.apache.http.Header;  
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.CookieStore;  
  8. import org.apache.http.client.config.AuthSchemes;  
  9. import org.apache.http.client.config.CookieSpecs;  
  10. import org.apache.http.client.config.RequestConfig;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.CloseableHttpResponse;  
  13. import org.apache.http.client.methods.HttpGet;  
  14. import org.apache.http.client.methods.HttpPost;  
  15. import org.apache.http.client.protocol.HttpClientContext;  
  16. import org.apache.http.config.Registry;  
  17. import org.apache.http.config.RegistryBuilder;  
  18. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  19. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  20. import org.apache.http.conn.ssl.NoopHostnameVerifier;  
  21. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  22. import org.apache.http.impl.client.*;  
  23. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  24. import org.apache.http.util.EntityUtils;  
  25.   
  26. import javax.net.ssl.SSLContext;  
  27. import javax.net.ssl.TrustManager;  
  28. import javax.net.ssl.X509TrustManager;  
  29. import java.io.IOException;  
  30. import java.security.KeyManagementException;  
  31. import java.security.NoSuchAlgorithmException;  
  32. import java.security.cert.CertificateException;  
  33. import java.security.cert.X509Certificate;  
  34. import java.util.ArrayList;  
  35. import java.util.Arrays;  
  36. import java.util.List;  
  37.   
  38. /** 
  39.  * Created by Administrator on 2015/11/28. 
  40.  */  
  41. public class HttpClientUtil {  
  42.     private static HttpClientContext context = HttpClientContext.create();  
  43.     private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)  
  44.             .setConnectionRequestTimeout(60000).setCookieSpec(CookieSpecs.STANDARD_STRICT).  
  45.                     setExpectContinueEnabled(true).  
  46.                     setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).  
  47.                     setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();  
  48.   
  49.     //https  
  50.     private static SSLConnectionSocketFactory socketFactory;  
  51.     private static TrustManager manager = new X509TrustManager() {  
  52.   
  53.         @Override  
  54.         public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  55.   
  56.         }  
  57.   
  58.         @Override  
  59.         public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  60.   
  61.         }  
  62.   
  63.         @Override  
  64.         public X509Certificate[] getAcceptedIssuers() {  
  65.             return null;  
  66.         }  
  67.     };  
  68.   
  69.     private static void enableSSL() {  
  70.         try {  
  71.             SSLContext sslContext = SSLContext.getInstance("TLS");  
  72.             sslContext.init(nullnew TrustManager[]{manager}, null);  
  73.             socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);  
  74.         } catch (NoSuchAlgorithmException e) {  
  75.             e.printStackTrace();  
  76.         } catch (KeyManagementException e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80.   
  81.     /** 
  82.      * https get 
  83.      * @param url 
  84.      * @param data 
  85.      * @return 
  86.      * @throws java.io.IOException 
  87.      */  
  88.     public static CloseableHttpResponse doHttpsGet(String url, String data){  
  89.         enableSSL();  
  90.         Registry socketFactoryRegistry = RegistryBuilder.create()  
  91.                 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();  
  92.         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  93.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  
  94.                 .setDefaultRequestConfig(requestConfig).build();  
  95.         HttpGet httpGet = new HttpGet(url);  
  96.         CloseableHttpResponse response = null;  
  97.         try {  
  98.             response = httpClient.execute(httpGet, context);  
  99.         }catch (Exception e){  
  100.             e.printStackTrace();  
  101.         }  
  102.   
  103.         return response;  
  104.     }  
  105.   
  106.     /** 
  107.      * https post 
  108.      * @param url 
  109.      * @param values 
  110.      * @return 
  111.      * @throws java.io.IOException 
  112.      */  
  113.     public static CloseableHttpResponse doHttpsPost(String url, List values) {  
  114.         enableSSL();  
  115.         Registry socketFactoryRegistry = RegistryBuilder.create()  
  116.                 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();  
  117.         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  118.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  
  119.                 .setDefaultRequestConfig(requestConfig).build();  
  120.         HttpPost httpPost = new HttpPost(url);  
  121.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  122.         httpPost.setEntity(entity);  
  123.         CloseableHttpResponse response = null;  
  124.         try {  
  125.             response = httpClient.execute(httpPost, context);  
  126.         }catch (Exception e){}  
  127.         return response;  
  128.     }  
  129.   
  130.     /** 
  131.      * http get 
  132.      * 
  133.      * @param url 
  134.      * @param data 
  135.      * @return 
  136.      */  
  137.     public static CloseableHttpResponse doGet(String url, String data) {  
  138.         CookieStore cookieStore = new BasicCookieStore();  
  139.         CloseableHttpClient httpClient = HttpClientBuilder.create().  
  140.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  141.                 setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultHeaders(new ArrayList
    ()).  
  142.                 setDefaultCookieStore(cookieStore).  
  143.                 setDefaultRequestConfig(requestConfig).build();  
  144.   
  145.         HttpGet httpGet = new HttpGet(url);  
  146.         //httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");  
  147.         CloseableHttpResponse response = null;  
  148.         try {  
  149.             response = httpClient.execute(httpGet, context);  
  150.         }catch (Exception e){}  
  151.         return response;  
  152.     }  
  153.   
  154.     /** 
  155.      * http post 
  156.      * 
  157.      * @param url 
  158.      * @param values 
  159.      * @return 
  160.      */  
  161.     public static CloseableHttpResponse doPost(String url, List values) {  
  162.         CookieStore cookieStore = new BasicCookieStore();  
  163.         CloseableHttpClient httpClient = HttpClientBuilder.create().  
  164.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  165.                 setRedirectStrategy(new DefaultRedirectStrategy()).  
  166.                 setDefaultCookieStore(cookieStore).  
  167.                 setDefaultRequestConfig(requestConfig).build();  
  168.   
  169.         HttpPost httpPost = new HttpPost(url);  
  170.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  171.         httpPost.setEntity(entity);  
  172.         CloseableHttpResponse response = null;  
  173.         try {  
  174.             response = httpClient.execute(httpPost, context);  
  175.         }catch (Exception e){}  
  176.         return response;  
  177.     }  
  178.   
  179.   
  180.     /** 
  181.      * 直接把Response内的Entity内容转换成String 
  182.      * 
  183.      * @param httpResponse 
  184.      * @return 
  185.      */  
  186.     public static String toString(CloseableHttpResponse httpResponse) {  
  187.         // 获取响应消息实体  
  188.         String result = null;  
  189.         try {  
  190.             HttpEntity entity = httpResponse.getEntity();  
  191.             if (entity != null) {  
  192.                 result = EntityUtils.toString(entity,"UTF-8");  
  193.             }  
  194.         }catch (Exception e){}finally {  
  195.             try {  
  196.                 httpResponse.close();  
  197.             } catch (IOException e) {  
  198.                 e.printStackTrace();  
  199.             }  
  200.         }  
  201.         return result;  
  202.     }  
  203.   
  204.     public static void main(String[] args){  
  205.         CloseableHttpResponse response = HttpClientUtil.doHttpsGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb2ebe42765aad029&secret=720661590f720b1f501ab3f390f80d52","");  
  206.         System.out.println(HttpClientUtil.toString(response));  
  207.     }  
  208. }  

你可能感兴趣的:(HttpClient)