httpClient 工具

本文介绍了一个基于Apache HttpClient和commons-codec的Java HTTP客户端工具类,涵盖了GET和POST请求的发送,包括设置请求头、参数、超时时间和SSL连接配置。通过示例代码展示了如何使用该工具类进行HTTP请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 依赖jar 包

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>

2. 工具类

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import org.apache.commons.httpclient.Header;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;

@SuppressWarnings("deprecation")
public class HttpClientUtils {
	
	public static final String HTTPS = "https"; 
	public static final String HEADER = "HEADER"; 
	public static final String BODY = "body"; 
	public static final String UTF_8 = "UTF-8";

    public static final int CONN_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 10000;
    private static HttpClient client = null;
    
    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }
    
    
    /****************************************GET 请求 ************************************************************/
    public static String getBody(String url) {
    	return getBody(url, null);
    }
    
    public static String getBody(String url, Map<String, String> headers) {
    	Map<String, Object> resultMap =  sendGet(url, headers);
    	if (null != resultMap && !resultMap.isEmpty()) {
    		return (String)resultMap.get(BODY);
    	}
    	return null;
    } 
    
    public static Header[] getHeader(String url) {
    	return getHeader(url, null);
    }
    
    public static Header[] getHeader(String url, Map<String, String> headers) {
    	Map<String, Object> resultMap =  sendGet(url, headers);
    	if (null != resultMap && !resultMap.isEmpty()) {
    		return (Header[])resultMap.get(HEADER);
    	}
    	return null;
    } 
    
    
    /****************************************POST 请求 ************************************************************/
    public static String postBody(String url, String parameterStr){
    	Map<String, Object> resultMap =  sendPost(url, parameterStr, "application/x-www-form-urlencoded");
    	if (null != resultMap && !resultMap.isEmpty()) {
    		return (String)resultMap.get(BODY);
    	}
        return null;
    }
    
    public static Header[] postHeader(String url, String parameterStr){
    	Map<String, Object> resultMap =  sendPost(url, parameterStr, "application/x-www-form-urlencoded");
    	if (null != resultMap && !resultMap.isEmpty()) {
    		return (Header[])resultMap.get(HEADER);
    	}
        return null;
    }
    
    public static String postBody(String url, Map<String, String> params) {
        return postBody(url, params, null);
     }
    
    public static String postBody(String url, Map<String, String> params, Map<String, String> header) {
    	Map<String, Object> resultMap =  sendPostForm(url, params, header);
    	if (null != resultMap && !resultMap.isEmpty()) {
    		return (String)resultMap.get(BODY);
    	}
        return null;
     }
    
    /** 
     * 发送一个 Post 请求
     * @param url 
     * @param body RequestBody 
     * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
     * @param charset 编码 
     * @param connTimeout 建立链接超时时间,毫秒. 
     * @param readTimeout 响应超时时间,毫秒. 
     * @throws Exception 
     */  
    public static Map<String, Object> sendPost(String url, String body, String mimeType) {
        HttpClient httpClient = null;
        HttpResponse httpResponse = null;
        Map<String, Object> resultMap = new HashMap<>();  
        HttpPost httpPost = new HttpPost(url);  
   
        try {
            // 设置参数  
            Builder customReqConf = RequestConfig.custom();  
            customReqConf.setConnectTimeout(CONN_TIMEOUT);  
            customReqConf.setSocketTimeout(READ_TIMEOUT);  
            httpPost.setConfig(customReqConf.build());  
            
            //设置请求BODY
            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, UTF_8));
                httpPost.setEntity(entity);
            }
            if (url.startsWith(HTTPS)) {  
  				httpClient = createSSLInsecureClient();
              	httpResponse = httpClient.execute(httpPost);  
              } else {  
              	httpClient = client;
              	httpResponse = httpClient.execute(httpPost);  
              }
            resultMap.put(HEADER,  httpResponse.getAllHeaders());
            resultMap.put(BODY, IOUtils.toString(httpResponse.getEntity().getContent(), UTF_8));
        } catch (GeneralSecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {  
			try {
				httpPost.releaseConnection();  
	            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {  
	            	((CloseableHttpClient) client).close();
	            }
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return resultMap;
    }
    
    /** 
     * 提交form表单 
     *  
     * @param url 			请求URL
     * @param params 		请求参数
     * @param connTimeout 	连接超时
     * @param readTimeout 	读取超时
     */  
    public static Map<String, Object> sendPostForm(String url, Map<String, String> params, Map<String, String> headers) {  
        HttpClient httpClient = null;
        HttpResponse httpResponse = null;
        Map<String, Object> resultMap = new HashMap<>();  
        HttpPost httpPost = new HttpPost(url);  
        try {  
            // 设置参数  
            Builder customReqConf = RequestConfig.custom();  
            customReqConf.setConnectTimeout(CONN_TIMEOUT);  
            customReqConf.setSocketTimeout(READ_TIMEOUT);  
            httpPost.setConfig(customReqConf.build());  
            
            //设置请求头信息
            if (headers != null && !headers.isEmpty()) {  
                for (Entry<String, String> entry : headers.entrySet()) {  
                	httpPost.addHeader(entry.getKey(), entry.getValue());  
                }  
            }
            
            //设置请求参数信息
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);  
                httpPost.setEntity(entity);
            }
            if (url.startsWith(HTTPS)) {  
  				httpClient = createSSLInsecureClient();
              	httpResponse = httpClient.execute(httpPost);  
              } else {  
              	httpClient = client;
              	httpResponse = httpClient.execute(httpPost);  
              }
            resultMap.put(HEADER,  httpResponse.getAllHeaders());
            resultMap.put(BODY, IOUtils.toString(httpResponse.getEntity().getContent(), UTF_8));
        } catch (GeneralSecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {  
			try {
				httpPost.releaseConnection();  
	            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {  
	            	((CloseableHttpClient) client).close();
	            }
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return resultMap;  
    } 
    
    /** 
     * 发送一个 GET 请求 
     * @param url 
     * @param charset 
     * @param connTimeout  建立链接超时时间,毫秒. 
     * @param readTimeout  响应超时时间,毫秒. 
     */  
    public static Map<String, Object> sendGet(String url, Map<String, String> headers) { 
        HttpClient httpClient = null;  
        HttpResponse httpResponse = null;  
        Map<String, Object> resultMap = new HashMap<>();  
        HttpGet httpGet = new HttpGet(url);
        try {
        	// 设置请求参数
        	Builder customReqConf = RequestConfig.custom(); 
            customReqConf.setConnectTimeout(CONN_TIMEOUT);  
            customReqConf.setSocketTimeout(READ_TIMEOUT); 
            httpGet.setConfig(customReqConf.build());  
            //设置请求头信息
            if (headers != null && !headers.isEmpty()) {  
                for (Entry<String, String> entry : headers.entrySet()) {  
                	httpGet.addHeader(entry.getKey(), entry.getValue());  
                }  
            }
            if (url.startsWith(HTTPS)) {  
				httpClient = createSSLInsecureClient();
            	httpResponse = httpClient.execute(httpGet);  
            } else {  
            	httpClient = client;
            	httpResponse = httpClient.execute(httpGet);  
            }
            resultMap.put(HEADER,  httpResponse.getAllHeaders());
            resultMap.put(BODY, IOUtils.toString(httpResponse.getEntity().getContent(), UTF_8));
            return resultMap;
        } catch (GeneralSecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpGet.releaseConnection();  
	            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {  
	            	((CloseableHttpClient) client).close();
	            }
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return resultMap;  
    }  
    
/** 
KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\jiaoyiping.p12")), "123456".toCharArray());
        SSLContext sslcontext = SSLContexts.custom()
                //忽略掉对服务器端证书的校验
                .loadTrustMaterial(new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                })
                
                //加载服务端提供的truststore(如果服务器提供truststore的话就不用忽略对服务器端证书的校验了)
                //.loadTrustMaterial(new File("D:\\truststore.jks"), "123456".toCharArray(),
                //        new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore, "cmcc".toCharArray())
                .build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build();
       **/         
    
    /**
     * 创建 SSL连接
     * @return
     * @throws GeneralSecurityException
     */
    @SuppressWarnings("all")
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                        public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
                            return true;
                        }
                    }).build();
            
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                        @Override
                        public boolean verify(String arg0, SSLSession arg1) {
                            return true;
                        }

                        @Override
                        public void verify(String host, SSLSocket ssl)
                                throws IOException {
                        }

                        @Override
                        public void verify(String host, X509Certificate cert)
                                throws SSLException {
                        }

                        @Override
                        public void verify(String host, String[] cns,
                                String[] subjectAlts) throws SSLException {
                        }

                    });
            
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            
        } catch (GeneralSecurityException e) {
            throw e;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值