使用java調用http請求系列--HttpClient

簡介:該工具類使用HttpClient實現了調用http請求和支持https的調用方式。

1.使用HttpClient實現調用http和https請求:


import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.config.*;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * Created by admin on 2017/9/22.
 * 使用HttpClient實現了調用http和https請求
 */
public class HttpClientUtil {

    private static PoolingHttpClientConnectionManager connManager = null;
    public static HttpClientBuilder httpClientBuilder = null;

    public HttpClientUtil() {
    }

    public static PoolingHttpClientConnectionManager getConnManager() {
        return connManager;
    }

    public static HttpClientBuilder getHttpClientBuilder() {
        return httpClientBuilder;
    }

    public static CloseableHttpClient getCloseableHttpClient() {
        return httpClientBuilder.build();
    }

    public static String get(String url) {
        CloseableHttpResponse response = null;
        CloseableHttpClient closeableHttpClient = null;
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
        httpGet.setConfig(requestConfig);

        try {
            closeableHttpClient = getCloseableHttpClient();
            response = closeableHttpClient.execute(httpGet);
            int e = response.getStatusLine().getStatusCode();
            if(e != 200) {
                httpGet.abort();
            }
            HttpEntity entity = null;
            try {
                entity = response.getEntity();
                String var8 = EntityUtils.toString(entity, "utf-8");
                return var8;
            } finally {
                if(entity != null) {
                    EntityUtils.consume(entity);
                }
            }
        } catch (ClientProtocolException var28) {
            var28.printStackTrace();
        } catch (IOException var29) {
            var29.printStackTrace();
        } finally {
            if(null != response) {
                try {
                    response.close();
                } catch (IOException var26) {
                    var26.printStackTrace();
                }
            }
            if(null != httpGet) {
                httpGet.releaseConnection();
            }
        }
        return null;
    }

    public static String post(String url) {
        CloseableHttpResponse response = null;
        CloseableHttpClient closeableHttpClient = null;
        HttpPost httpGet = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
        httpGet.setConfig(requestConfig);

        try {
            closeableHttpClient = getCloseableHttpClient();
            response = closeableHttpClient.execute(httpGet);
            int e = response.getStatusLine().getStatusCode();
            if(e != 200) {
                httpGet.abort();
            }
            HttpEntity entity = null;
            try {
                entity = response.getEntity();
                String var8 = EntityUtils.toString(entity, "utf-8");
                return var8;
            } finally {
                if(entity != null) {
                    EntityUtils.consume(entity);
                }
            }
        } catch (ClientProtocolException var28) {
            var28.printStackTrace();
        } catch (IOException var29) {
            var29.printStackTrace();
        } finally {
            if(null != response) {
                try {
                    response.close();
                } catch (IOException var26) {
                    var26.printStackTrace();
                }
            }
            if(null != httpGet) {
                httpGet.releaseConnection();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String result = get("https://www.baidu.com");
        System.out.println(result);
    }

    static {
        try {
            SSLContext e = SSLContexts.custom().useSSL().build();
            e.init((KeyManager[])null, new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            }, (SecureRandom)null);
            Registry socketFactoryRegistry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(e)).build();
            connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
            connManager.setDefaultSocketConfig(socketConfig);
            MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
            ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(messageConstraints).build();
            connManager.setDefaultConnectionConfig(connectionConfig);
            connManager.setMaxTotal(200);
            connManager.setDefaultMaxPerRoute(20);
            httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setConnectionManager(connManager);
        } catch (KeyManagementException var5) {
            var5.printStackTrace();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
        }
    }

}

2.使用java實現調用http請求,不支持https:


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/9/25.
 * 使用HttpClient實現了調用http請求,不支持https
 */
public class HttpClientUtil2 {

    public static String requestHttpGet(String url){
        CloseableHttpClient httpClient = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode!=200){
                httpGet.abort();
            }
            HttpEntity httpEntity = null;
            try {
                httpEntity = httpResponse.getEntity();
                InputStream in = httpEntity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                while ((line=reader.readLine())!=null){
                    result += line;
                }
                /*result = EntityUtils.toString(httpEntity, "utf-8");
                return result;*/
            } finally {
                if(httpEntity != null) {
                    EntityUtils.consume(httpEntity);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (httpClient!=null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String requestHttpPost(String url,Map<String,String> params){
        CloseableHttpClient httpClient = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            //添加參數
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            if (params!=null && !params.isEmpty()){
                for (String s : params.keySet()) {
                    list.add(new BasicNameValuePair(s,params.get(s)));
                }
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,"utf-8");
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode!=200){
                httpPost.abort();
            }
            HttpEntity httpEntity = null;
            try {
                httpEntity = httpResponse.getEntity();
                InputStream in = httpEntity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                while ((line=reader.readLine())!=null){
                    result += line;
                }
                /*result = EntityUtils.toString(httpEntity, "utf-8");
                return result;*/
            } finally {
                if(httpEntity != null) {
                    EntityUtils.consume(httpEntity);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (httpClient!=null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(requestHttpGet("http://www.baidu.com"));
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章