天天看點

HttpClient 發送POST,GET請求

引入maven檔案

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.1</version>
</dependency>
           

使用httpclient發送帶參數的請求

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
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.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
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.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 *  apache httpclient 工具類
 *  支援對 http https 接口調用
 *  <P>
 *      1.GET 請求
 *      2.POST 請求
 *  </P>
 */
public class HttpDelegate {
    private int timeOut = 10000;//指定逾時時間
    private CloseableHttpClient httpClient;
    private RequestConfig requestConfig;//設定請求參數

    /**
     * 對象被建立時執行
     */
    public HttpDelegate(Boolean isHttps){
        httpClient = this.getHttpClient(isHttps);
        this.initRequestConfig();//初始化請求配置
    }

    /**
     * 發送post請求
     * @param url 請求位址
     * @param contentType 請求類型
     * @param encoding 編碼格式
     * @param param 請求參數
     * @return
     */
    public String executePost(String url,String contentType,String encoding,String param)
    {
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setConfig(requestConfig);
            this.initMethodParam(httpPost, contentType, encoding);
            if(param!=null)
            {
                httpPost.setEntity(new StringEntity(param, encoding));//設定請求體
            }
            return this.execute(httpPost,httpClient);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e.getMessage(), e);
        }
        finally
        {
            httpPost.releaseConnection();
        }
    }

    /**
     * 發送get請求
     * @param url 請求位址
     * @param contentType 請求類型
     * @param encoding 編碼格式
     * @return
     */
    public String executeGet(String url,String contentType,String encoding){
        HttpGet httpGet = new HttpGet(url);
        try{
            httpGet.setConfig(requestConfig);
            this.initMethodParam(httpGet, contentType, encoding);
            return this.execute(httpGet,httpClient);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(),e);
        }finally{
            httpGet.releaseConnection();
        }
    }
    /**
     * 通用方法,用來發送post或get請求
     * @param method 請求類型
     * @param httpClient
     * @return
     * @throws RuntimeException
     * @throws IOException
     */
    private String execute(HttpUriRequest method,CloseableHttpClient httpClient) throws RuntimeException,IOException{
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(method);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, method.getFirstHeader(HttpHeaders.CONTENT_ENCODING).getValue());
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(), e);
        }finally{
            if(response != null){
                response.close();
            }
        }
    }

    private void initMethodParam(HttpUriRequest method, String contentType, String encoding){
        if (contentType != null){
            method.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
        }
        method.setHeader(HttpHeaders.CONTENT_ENCODING, encoding);
        method.setHeader(HttpHeaders.TIMEOUT, "60000");
    }

    /**
     * 設定初始值
     */
    private void initRequestConfig() {
        requestConfig=RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
    }

    /**
     * 擷取主體類:
     * isHttps 區分https 和 https
     * @param isHttps
     * @return
     */
    private CloseableHttpClient getHttpClient(boolean isHttps) {
        CloseableHttpClient chc = null;
        try{
            if (isHttps){
                TrustManager[] trustManagers = new TrustManager[1];
                trustManagers[0] = new X509TrustManager(){
                    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
                    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
                    public X509Certificate[] getAcceptedIssuers(){
                        return null;
                    }
                };
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
                SSLContext.setDefault(sslContext);
                sslContext.init(null, trustManagers, null);
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                chc = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            }else{
                chc=HttpClients.custom().build();
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(), e);
        }
        return chc;
    }

    /**
     * 關閉連結
     */
    public void destroy(){
        System.out.println("方法被執行");
        try{
            httpClient.close();
        }catch (IOException e){
            throw new RuntimeException(e.getMessage(),e);
        }
    }
}
           

繼續閱讀