1. 程式人生 > >HttpClient實現同步(sync)和非同步(Async)

HttpClient實現同步(sync)和非同步(Async)

pom:

<httpclient.version>4.5</httpclient.version>

<http-async-client.version>4.1</http-async-client.version>
<dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>


        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpasyncclient</artifactId>
            <version>${http-async-client.version}</version>
        </dependency>


        <!-- http client -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpclient.version}</version>
        </dependency>


        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>${httpclient.version}</version>
        </dependency>
    </dependencies>
<dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpasyncclient</artifactId>
            <version>${http-async-client.version}</version>
        </dependency>

        <!-- http client -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpclient.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>${httpclient.version}</version>
        </dependency>
    </dependencies>

java:async

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package com.xxx.emidas.monitor.api.util;  
  2. import org.apache.http.*;  
  3. import org.apache.http.client.CookieStore;  
  4. import org.apache.http.client.config.AuthSchemes;  
  5. import org.apache.http.client.config.CookieSpecs;  
  6. import org.apache.http.client.config.RequestConfig;  
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  8. import org.apache.http.client.methods.CloseableHttpResponse;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.client.protocol.HttpClientContext;  
  12. import org.apache.http.concurrent.FutureCallback;  
  13. import org.apache.http.config.Registry;  
  14. import org.apache.http.config.RegistryBuilder;  
  15. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  16. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  17. import org.apache.http.conn.ssl.NoopHostnameVerifier;  
  18. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  19. import org.apache.http.impl.client.*;  
  20. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  21. import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;  
  22. import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;  
  23. import org.apache.http.impl.nio.client.HttpAsyncClients;  
  24. import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;  
  25. import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;  
  26. import org.apache.http.util.EntityUtils;  
  27. import javax.net.ssl.SSLContext;  
  28. import javax.net.ssl.TrustManager;  
  29. import javax.net.ssl.X509TrustManager;  
  30. import java.io.IOException;  
  31. import java.io.InputStream;  
  32. import java.io.InputStreamReader;  
  33. import java.io.Reader;  
  34. import java.security.KeyManagementException;  
  35. import java.security.NoSuchAlgorithmException;  
  36. import java.security.cert.CertificateException;  
  37. import java.security.cert.X509Certificate;  
  38. import java.util.ArrayList;  
  39. import java.util.Arrays;  
  40. import java.util.List;  
  41. import java.util.concurrent.Future;  
  42. /** 
  43.  * Created by Administrator on 2015/11/28. 
  44.  */
  45. publicclass HttpAsyncClientUtil {  
  46.     privatestatic HttpClientContext context = HttpClientContext.create();  
  47.     /** 
  48.      * http async get 
  49.      * 
  50.      * @param url 
  51.      * @param data 
  52.      * @return 
  53.      */
  54.     publicstaticvoid doGet(String url, String data) {  
  55.         CookieStore cookieStore = new BasicCookieStore();  
  56.         final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();  
  57.         httpClient.start();  
  58.         HttpGet httpGet = new HttpGet(url);  
  59.         //httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
  60.         try {  
  61.             httpClient.execute(httpGet, context, new FutureCallback<HttpResponse>() {  
  62.                 @Override
  63.                 publicvoid completed(HttpResponse result) {  
  64.                     String body="";  
  65.                     //這裡使用EntityUtils.toString()方式時會大概率報錯,原因:未接受完畢,連結已關
  66.                     try {  
  67.                         HttpEntity entity = result.getEntity();  
  68.                         if (entity != null) {  
  69.                             final InputStream instream = entity.getContent();  
  70.                             try {  
  71.                                 final StringBuilder sb = new StringBuilder();  
  72.                                 finalchar[] tmp = newchar[1024];  
  73.                                 final Reader reader = new InputStreamReader(instream,"UTF-8");  
  74.                                 int l;  
  75.                                 while ((l = reader.read(tmp)) != -1) {  
  76.                                     sb.append(tmp, 0, l);  
  77.                                 }  
  78.                                 body = sb.toString();  
  79.                                 System.out.println(body);  
  80.                             } finally {  
  81.                                 instream.close();  
  82.                                 EntityUtils.consume(entity);  
  83.                             }  
  84.                         }  
  85.                     } catch (ParseException e) {  
  86.                         e.printStackTrace();  
  87.                     }catch (IOException e) {  
  88.                         e.printStackTrace();  
  89.                     }finally {  
  90.                         close(httpClient);  
  91.                     }  
  92.                 }  
  93.                 @Override
  94.                 publicvoid failed(Exception ex) {  
  95.                     System.out.println(ex.toString());  
  96.                     close(httpClient);  
  97.                 }  
  98.                 @Override
  99.                 publicvoid cancelled() {  
  100.                 }  
  101.             });  
  102.         } catch (Exception e) {  
  103.         }  
  104.         System.out.println("end-----------------------");  
  105.     }  
  106.     /** 
  107.      * http async post 
  108.      * 
  109.      * @param url 
  110.      * @param values 
  111.      * @return 
  112.      */
  113.     publicstaticvoid doPost(String url, List<NameValuePair> values) {  
  114.         CookieStore cookieStore = new BasicCookieStore();  
  115.         CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();  
  116.         HttpPost httpPost = new HttpPost(url);  
  117.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  118.         httpPost.setEntity(entity);  
  119.         try {  
  120.             httpClient.execute(httpPost, context, new FutureCallback<HttpResponse>() {  
  121.                 @Override
  122.                 publicvoid completed(HttpResponse result) {  
  123.                     System.out.println(result.toString());  
  124.                 }  
  125.                 @Override
  126.                 publicvoid failed(Exception ex) {  
  127.                     System.out.println(ex.toString());  
  128.                 }  
  129.                 @Override
  130.                 publicvoid cancelled() {  
  131.                 }  
  132.             });  
  133.         } catch (Exception e) {  
  134.         }  
  135.     }  
  136.     privatestaticvoid close(CloseableHttpAsyncClient client) {  
  137.         try {  
  138.             client.close();  
  139.         } catch (IOException e) {  
  140.             e.printStackTrace();  
  141.         }  
  142.     }  
  143.     /** 
  144.      * 直接把Response內的Entity內容轉換成String 
  145.      * 
  146.      * @param httpResponse 
  147.      * @return 
  148.      */
  149.     publicstatic String toString(CloseableHttpResponse httpResponse) {  
  150.         // 獲取響應訊息實體
  151.         String result = null;  
  152.         try {  
  153.             HttpEntity entity = httpResponse.getEntity();  
  154.             if (entity != null) {  
  155.                 result = EntityUtils.toString(entity, "UTF-8");  
  156.             }  
  157.         } catch (Exception e) {  
  158.         } finally {  
  159.             try {  
  160.                 httpResponse.close();  
  161.             } catch (IOException e) {  
  162.                 e.printStackTrace();  
  163.             }  
  164.         }  
  165.         return result;  
  166.     }  
  167.     publicstaticvoid main(String[] args) throws Exception{  
  168.         CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();  
  169.         try {  
  170.             httpclient.start();  
  171.             HttpGet request = new HttpGet("http://www.apache.org/");  
  172.             Future<HttpResponse> future = httpclient.execute(request, null);  
  173.             HttpResponse response = future.get();  
  174.             System.out.println("Response: " + response.getStatusLine());  
  175.             System.out.println("Shutting down");  
  176.         } finally {  
  177.             httpclient.close();  
  178.         }  
  179.         System.out.println("Done");  
  180.     }  
  181. }  
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<HttpResponse>() {
                @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<NameValuePair> 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<HttpResponse>() {
                @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<HttpResponse> 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?在CODE上檢視程式碼片派生到我的程式碼片
  1. package com.xxx.emidas.monitor.api.util;  
  2. import org.apache.http.Consts;  
  3. import org.apache.http.Header;  
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.NameValuePair;  
  6. import org.apache.http.client.CookieStore;  
  7. import org.apache.http.client.config.AuthSchemes;  
  8. import org.apache.http.client.config.CookieSpecs;  
  9. import org.apache.http.client.config.RequestConfig;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.CloseableHttpResponse;  
  12. import org.apache.http.client.methods.HttpGet;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.client.protocol.HttpClientContext;  
  15. import org.apache.http.config.Registry;  
  16. import org.apache.http.config.RegistryBuilder;  
  17. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  18. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  19. import org.apache.http.conn.ssl.NoopHostnameVerifier;  
  20. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  21. import org.apache.http.impl.client.*;  
  22. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  23. import org.apache.http.util.EntityUtils;  
  24. import javax.net.ssl.SSLContext;  
  25. import javax.net.ssl.TrustManager;  
  26. import javax.net.ssl.X509TrustManager;  
  27. import java.io.IOException;  
  28. import java.security.KeyManagementException;  
  29. import java.security.NoSuchAlgorithmException;  
  30. import java.security.cert.CertificateException;  
  31. import java.security.cert.X509Certificate;  
  32. import java.util.ArrayList;  
  33. import java.util.Arrays;  
  34. import java.util.List;  
  35. /** 
  36.  * Created by Administrator on 2015/11/28. 
  37.  */
  38. publicclass HttpClientUtil {  
  39.     privatestatic HttpClientContext context = HttpClientContext.create();  
  40.     privatestatic RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)  
  41.             .setConnectionRequestTimeout(60000).setCookieSpec(CookieSpecs.STANDARD_STRICT).  
  42.                     setExpectContinueEnabled(true).  
  43.                     setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).  
  44.                     setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();  
  45.     //https
  46.     privatestatic SSLConnectionSocketFactory socketFactory;  
  47.     privatestatic TrustManager manager = new X509TrustManager() {  
  48.         @Override
  49.         publicvoid checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  50.         }  
  51.         @Override
  52.         publicvoid checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  53.         }  
  54.         @Override
  55.         public X509Certificate[] getAcceptedIssuers() {  
  56.             returnnull;  
  57.         }  
  58.     };  
  59.     privatestaticvoid enableSSL() {  
  60.         try {  
  61.             SSLContext sslContext = SSLContext.getInstance("TLS");  
  62.             sslContext.init(nullnew TrustManager[]{manager}, null);  
  63.             socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);  
  64.         } catch (NoSuchAlgorithmException e) {  
  65.             e.printStackTrace();  
  66.         } catch (KeyManagementException e) {  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70.     /** 
  71.      * https get 
  72.      * @param url 
  73.      * @param data 
  74.      * @return 
  75.      * @throws java.io.IOException 
  76.      */
  77.     publicstatic CloseableHttpResponse doHttpsGet(String url, String data){  
  78.         enableSSL();  
  79.         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
  80.                 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();  
  81.         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  82.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  
  83.                 .setDefaultRequestConfig(requestConfig).build();  
  84.         HttpGet httpGet = new HttpGet(url);  
  85.         CloseableHttpResponse response = null;  
  86.         try {  
  87.             response = httpClient.execute(httpGet, context);  
  88.         }catch (Exception e){  
  89.             e.printStackTrace();  
  90.         }  
  91.         return response;  
  92.     }  
  93.     /** 
  94.      * https post 
  95.      * @param url 
  96.      * @param values 
  97.      * @return 
  98.      * @throws java.io.IOException 
  99.      */
  100.     publicstatic CloseableHttpResponse doHttpsPost(String url, List<NameValuePair> values) {  
  101.         enableSSL();  
  102.         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
  103.                 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();  
  104.         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  105.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  
  106.                 .setDefaultRequestConfig(requestConfig).build();  
  107.         HttpPost httpPost = new HttpPost(url);  
  108.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  109.         httpPost.setEntity(entity);  
  110.         CloseableHttpResponse response = null;  
  111.         try {  
  112.             response = httpClient.execute(httpPost, context);  
  113.         }catch (Exception e){}  
  114.         return response;  
  115.     }  
  116.     /** 
  117.      * http get 
  118.      * 
  119.      * @param url 
  120.      * @param data 
  121.      * @return 
  122.      */
  123.     publicstatic CloseableHttpResponse doGet(String url, String data) {  
  124.         CookieStore cookieStore = new BasicCookieStore();  
  125.         CloseableHttpClient httpClient = HttpClientBuilder.create().  
  126.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  127.                 setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultHeaders(new ArrayList<Header>()).  
  128.                 setDefaultCookieStore(cookieStore).  
  129.                 setDefaultRequestConfig(requestConfig).build();  
  130.         HttpGet httpGet = new HttpGet(url);  
  131.         //httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
  132.         CloseableHttpResponse response = null;  
  133.         try {  
  134.             response = httpClient.execute(httpGet, context);  
  135.         }catch (Exception e){}  
  136.         return response;  
  137.     }  
  138.     /** 
  139.      * http post 
  140.      * 
  141.      * @param url 
  142.      * @param values 
  143.      * @return 
  144.      */
  145.     publicstatic CloseableHttpResponse doPost(String url, List<NameValuePair> values) {  
  146.         CookieStore cookieStore = new BasicCookieStore();  
  147.         CloseableHttpClient httpClient = HttpClientBuilder.create().  
  148.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  149.                 setRedirectStrategy(new DefaultRedirectStrategy()).  
  150.                 setDefaultCookieStore(cookieStore).  
  151.                 setDefaultRequestConfig(requestConfig).build();  
  152.         HttpPost httpPost = new HttpPost(url);  
  153.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  154.         httpPost.setEntity(entity);  
  155.         CloseableHttpResponse response = null;  
  156.         try {  
  157.             response = httpClient.execute(httpPost, context);  
  158.         }catch (Exception e){}  
  159.         return response;  
  160.     }  
  161.     /** 
  162.      * 直接把Response內的Entity內容轉換成String 
  163.      * 
  164.      * @param httpResponse 
  165.      * @return 
  166.      */
  167.     publicstatic String toString(CloseableHttpResponse httpResponse) {  
  168.         // 獲取響應訊息實體
  169.         String result = null;  
  170.         try {  
  171.             HttpEntity entity = httpResponse.getEntity();  
  172.             if (entity != null) {  
  173.                 result = EntityUtils.toString(entity,"UTF-8");  
  174.             }  
  175.         }catch (Exception e){}finally {  
  176.             try {  
  177.                 httpResponse.close();  
  178.             } catch (IOException e) {  
  179.                 e.printStackTrace();  
  180.             }  
  181.         }  
  182.         return result;  
  183.     }  
  184.     publicstaticvoid main(String[] args){  
  185.         CloseableHttpResponse response = HttpClientUtil.doHttpsGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb2ebe42765aad029&secret=720661590f720b1f501ab3f390f80d52","");  
  186.         System.out.println(HttpClientUtil.toString(response));  
  187.     }  
  188. }  

相關推薦

HttpClient實現同步(sync)非同步(Async)

pom: <httpclient.version>4.5</httpclient.version> <http-async-client.version>4.1</http-async-client.version> &

【Verilog】 同步復位非同步復位比較 async vs. sync

  同步復位 sync 非同步復位 async 特點 復位訊號只有在時鐘上升沿到來時才能有效。 無論時鐘沿是否到來,只要復位訊號有效,就進行復位。

同步FIFO非同步FIFO的Verilog實現

module fifo2 (rdata, wfull, rempty, wdata, winc, wclk, wrst_n, rinc, rclk, rrst_n); parameter DSIZE = 8; parameter ASIZE = 4; output [DSIZE-1:0] rdata; out

easyui的combotree同步非同步實現方法

<select class="easyui-combotree" id="acceptOrgNo" name="acceptOrgNo" style="width:300px" data-options="url:'glCaseInfo.ered?reqCode=zf

C# 委託的同步呼叫非同步呼叫--抓住重點

委託的Invoke方法用來進行同步呼叫。同步呼叫也可以叫阻塞呼叫,它將阻塞當前執行緒,然後執行呼叫,呼叫完畢後再繼續向下進行。 同步呼叫的例子: using System; using System.Threading; public delegate int AddHandl

tensorflow原始碼學習之五 -- 同步訓練非同步訓練

 同步和非同步訓練是由optimizer來決定的。         1. 同步訓練         同步訓練需要使用SyncReplicasOptimizer,參考https://www.tensorflow.org

執行緒同步非同步鎖的幾種方式

同步鎖:當在一個java虛擬機器多個執行緒操作一個變數的時候就會出現執行緒安全問題,這個時候就會用到同步鎖。 同步鎖的解決方式: 先看下一個執行緒異常的售票 public class ThreadSafe { public static void main(String[] arg

Mysql 半同步複製非同步複製

mysql 半同步複製和非同步複製 -- 在主庫中安裝半同步外掛,開啟半同步複製功能 install plugin rpl_semi_sync_master soname 'semisync_master.so'; set global rpl_semi_sync_master_enab

extjs中Ext.Ajax.request同步請求非同步請求

用Ext.Ajax.request請求預設是非同步請求,這就導致定義的物件無法識別,沒有定義,因此需要將請求方式改為同步。請看程式碼。 function showFormPanel(){ if(centerPanel.getSelectionModel().hasSelection()){

事務@Transactional非同步@Async註解失效

問題場景重現 場景一: Spring的非同步執行註解@Async,在呼叫這個方法的時候發現,不對勁,耗時的邏輯我已經加入到非同步取做了,怎麼介面請求的響應這麼慢,趕緊看日誌,懵X,加了非同步註解,卻沒有非同步執行。 場景二: 在專案中用到@Transactional註

同步IO非同步IO、阻塞IO非阻塞IO

1、IO        IO (Input/Output,輸入/輸出)即資料的讀取(接收)或寫入(傳送)操作,通常使用者程序中的一個完整IO分為兩階段:使用者程序空

同步IO非同步IO

程式碼:VOID WINAPI APC_A ( DWORD dwError, DWORD cbTransferred, LPOVERLAPPED lpo ){  pTempInfo.push_back ( "執行IO_A的完成例程" ) ;}VOID WINAPI APC_B ( DWORD dwError,

同步任務非同步任務

程式裡面所有的任務,可以分成兩類:同步任務和非同步任務   同步任務是那些沒有被引擎掛起,在主執行緒上排隊執行的任務。 只有前一個任務執行完畢,才能執行後一個任務。  非同步任務是那些被引擎放在一邊,不進去主執行緒、而進入任務佇列的任務。只有 引擎認為某個非同

網路程式設計中,同步傳輸非同步傳輸有什麼區別

在網路通訊過程中,通訊雙方要交換資料,需要高度的協同工作。為了正確的解釋訊號,接收方必須確切地知道訊號應當何時接收和處理,因此定時是至關重要的。 在計算機網路中,定時的因素稱為位同步。同步是要接收方按照發送方傳送的每個位的起止時刻和速率來接收資料,否則會產生誤差。 通常可以

從後臺獲得資料,前臺實現資料載入非同步查詢

前臺頁面大體是這樣的 預設載入指定頁籤的第一頁資料, 單擊頂部頁籤時,非同步請求相應的第一頁資料 單擊底部頁碼時,非同步請求對應頁碼的資料 單擊前進和後退時,對應請求相關資料和按鈕的禁用狀態 php部分 <?php 思路:未提交頁籤則預

okhttp 同步請求非同步請求

一、使用OkHttp OkHttp傳送請求後,可以通過同步或非同步地方式獲取響應。下面就同步和非同步兩種方式進行介紹。 1.1、同步方式 傳送請求後,就會進入阻塞狀態,知道收到響應。下面看一個下載百度首頁的例子: OkHttpClient client = new

form表單同步提交非同步提交

同步提交: html: <form id="form" method='"post" action="${ctx}/user/saveUser"> <input type=

Ajax實現區域性重新整理非同步處理簡單應用(實現簡單註冊驗證)

4.//從資料庫中查詢相應欄位並反饋給servlet 部分 @SuppressWarnings({ "unused", "null" })  public User find(String name){   List<Map<String,Object>> lists=new Arra

web中的同步請求非同步請求的差別(重點是ajax中的同步非同步)

此前,對於web中同步請求和非同步請求的概念模糊不清,不過對於這樣的知識盲點,不去克服的話都不好意思說自己是一名前端開發人員了[捂臉][捂臉]。還好,功夫不負有心人。通過自己的方式終於讓自己理解了,這兩個概念,因此,也想把自己的理解作博文,跟大家分享,如果說的不對,還請各位

同步呼叫非同步呼叫

我們知道,常見的方法呼叫都是同步呼叫,這種呼叫方式是一種阻塞式的呼叫方式,即客戶端(主呼叫方)程式碼一直阻塞等待直到被服務端(被呼叫方)返回 為止。這種呼叫方式相對比較直觀,也是大部分程式語言直接支援的一種呼叫方式。但是,如果我們面對是基於粗粒度的服務元件,面對的是一些需