`
hbxflihua
  • 浏览: 678483 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

基于httpclient4.5.3的httpsUtil

阅读更多

基于httpclient4.5.3的httpsUtil工具类

 

1、引入httpclient所需jar

		<!-- httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.5.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.6</version>
		</dependency>

 

2、httpsUtil工具类

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
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.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.DefaultCookieSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

class AnyTrustStrategy implements TrustStrategy{

	@Override
	public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
			throws java.security.cert.CertificateException {
		return true;
	}

}

public class HttpsUtil {

    private static final Log log= LogFactory.getLog(HttpsUtil.class);

    private static int bufferSize= 1024;

    private static volatile HttpsUtil instance;

    private volatile CloseableHttpClient client;

    private volatile BasicCookieStore cookieStore;

    public static String defaultEncoding= "utf-8";

    private static List<NameValuePair> paramsConverter(Map<String, String> params){
        List<NameValuePair> nvps = new LinkedList<NameValuePair>();
        Set<Entry<String, String>> paramsSet= params.entrySet();
        for (Entry<String, String> paramEntry : paramsSet) {
            nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
        }
        return nvps;
    }

    public static String readStream(InputStream in, String encoding){
        if (in == null){
            return null;
        }
        try {
            InputStreamReader inReader= null;
            if (encoding == null){
                inReader= new InputStreamReader(in, defaultEncoding);
            }else{
                inReader= new InputStreamReader(in, encoding);
            }
            char[] buffer= new char[bufferSize];
            int readLen= 0;
            StringBuffer sb= new StringBuffer();
            while((readLen= inReader.read(buffer))!=-1){
                sb.append(buffer, 0, readLen);
            }
            inReader.close();
            return sb.toString();
        } catch (IOException e) {
            log.error("读取返回内容出错", e);
        }
        return null;
    }

    private HttpsUtil()throws Exception{
        
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new AnyTrustStrategy());
		
		HostnameVerifier hostnameVerifierAllowAll = new HostnameVerifier() {
			@Override
			public boolean verify(String name, SSLSession session) {
				return true;
			}
		};
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
				new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, hostnameVerifierAllowAll);

		HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
			public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
				// 重试设置
				if (executionCount >= 5) {
					// Do not retry if over max retry count
					return false;
				}
				if (exception instanceof InterruptedIOException) {
					// Timeout
					return false;
				}
				if (exception instanceof UnknownHostException) {
					// Unknown host
					return false;
				}
				if (exception instanceof ConnectTimeoutException) {
					// Connection refused
					return false;
				}
				if (exception instanceof SSLException) {
					// SSL handshake exception
					return false;
				}
				HttpClientContext clientContext = HttpClientContext.adapt(context);
				HttpRequest request = clientContext.getRequest();
				boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
				if (idempotent) {
					return true;
				}
				return false;
			}
		};
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(120000)// 超时设置
				.build();
		client = HttpClients.custom().setSSLSocketFactory(sslsf).setRetryHandler(myRetryHandler)// 重试设置
				.setDefaultRequestConfig(requestConfig).build();
    }

    public static HttpsUtil getInstance(){
        synchronized (HttpsUtil.class) {
            if (HttpsUtil.instance == null){
                try {
					instance = new HttpsUtil();
				} catch (Exception e) {	}
            }
            return instance;
        }
    }

    public InputStream doGet(String url) throws URISyntaxException, ClientProtocolException, IOException{
        HttpResponse response= this.doGet(url, null);
        return response!=null ? response.getEntity().getContent() : null;
    }

    public String doGetForString(String url) throws URISyntaxException, ClientProtocolException, IOException{
        return HttpsUtil.readStream(this.doGet(url), null);
    }

    public InputStream doGetForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
        HttpResponse response= this.doGet(url, queryParams);
        return response!=null ? response.getEntity().getContent() : null;
    }

    public String doGetForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
        return HttpsUtil.readStream(this.doGetForStream(url, queryParams), null);
    }

    /**
     * 基本的Get请求
     * @param url 请求url
     * @param queryParams 请求头的查询参数
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public HttpResponse doGet(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
        HttpGet gm = new HttpGet();
        URIBuilder builder = new URIBuilder(url);
        //填入查询参数
        if (queryParams!=null && !queryParams.isEmpty()){
            builder.setParameters(HttpsUtil.paramsConverter(queryParams));
        }
        gm.setURI(builder.build());
        return client.execute(gm);
    }

    public InputStream doPostForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException {
        HttpResponse response = this.doPost(url, queryParams, null);
        return response!=null ? response.getEntity().getContent() : null;
    }

    public String doPostForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException {
        return HttpsUtil.readStream(this.doPostForStream(url, queryParams), null);
    }

    public InputStream doPostForStream(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
        HttpResponse response = this.doPost(url, queryParams, formParams);
        return response!=null ? response.getEntity().getContent() : null;
    }

    public String doPostRetString(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
        return HttpsUtil.readStream(this.doPostForStream(url, queryParams, formParams), null);
    }

    /**
     * 基本的Post请求
     * @param url 请求url
     * @param queryParams 请求头的查询参数
     * @param formParams post表单的参数
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public HttpResponse doPost(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
        HttpPost pm = new HttpPost();
        URIBuilder builder = new URIBuilder(url);
        //填入查询参数
        if (queryParams!=null && !queryParams.isEmpty()){
            builder.setParameters(HttpsUtil.paramsConverter(queryParams));
        }
        pm.setURI(builder.build());
        //填入表单参数
        if (formParams!=null && !formParams.isEmpty()){
            pm.setEntity(new UrlEncodedFormEntity(HttpsUtil.paramsConverter(formParams),defaultEncoding));
        }
        return client.execute(pm);
    }

    /**
     * 多块Post请求
     * @param url 请求url
     * @param queryParams 请求头的查询参数
     * @param formParts post表单的参数,支持字符串-文件(FilePart)和字符串-字符串(StringPart)形式的参数
     * @throws URISyntaxException
     * @throws ClientProtocolException
     * @throws HttpException
     * @throws IOException
     */
    public HttpResponse multipartPost(String url, Map<String, String> queryParams, List<FormBodyPart> formParts) throws URISyntaxException, ClientProtocolException, IOException{
        HttpPost pm= new HttpPost();
        URIBuilder builder = new URIBuilder(url);
        //填入查询参数
        if (queryParams!=null && !queryParams.isEmpty()){
            builder.setParameters(HttpsUtil.paramsConverter(queryParams));
        }
        pm.setURI(builder.build());
        //填入表单参数
        if (formParts!=null && !formParts.isEmpty()){
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder = entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (FormBodyPart formPart : formParts) {
                entityBuilder = entityBuilder.addPart(formPart.getName(), formPart.getBody());
            }
            pm.setEntity(entityBuilder.build());
        }
        return client.execute(pm);
    }

    /**
     * 获取当前Http客户端状态中的Cookie
     * @param domain 作用域
     * @param port 端口 传null 默认80
     * @param path Cookie路径 传null 默认"/"
     * @param useSecure Cookie是否采用安全机制 传null 默认false
     * @return
     */
    public Map<String, Cookie> getCookie(String domain, Integer port, String path, Boolean useSecure){
        if (domain == null){
            return null;
        }
        if (port==null){
            port= 80;
        }
        if (path==null){
            path="/";
        }
        if (useSecure==null){
            useSecure= false;
        }
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies==null || cookies.isEmpty()){
            return null;
        }

        CookieOrigin origin= new CookieOrigin(domain, port, path, useSecure);
        DefaultCookieSpec cookieSpec = new DefaultCookieSpec(null, false);
        Map<String, Cookie> retVal= new HashMap<String, Cookie>();
        for (Cookie cookie : cookies) {
            if(cookieSpec.match(cookie, origin)){
                retVal.put(cookie.getName(), cookie);
            }
        }
        return retVal;
    }

    /**
     * 批量设置Cookie
     * @param outCookies cookie键值对图
     * @param domain 作用域 不可为空
     * @param path 路径 传null默认为"/"
     * @param useSecure 是否使用安全机制 传null 默认为false
     * @return 是否成功设置cookie
     */
    public boolean setCookie(Map<String, String> outCookies, String domain, String path, Boolean useSecure){
        synchronized (cookieStore) {
            if (domain==null){
                return false;
            }
            if (path==null){
                path= "/";
            }
            if (useSecure==null){
                useSecure= false;
            }
            if (outCookies==null || outCookies.isEmpty()){
                return true;
            }
            Set<Entry<String, String>> set= outCookies.entrySet();
            List<Cookie> cookies = cookieStore.getCookies();
			for (int i = 0; i < cookies.size(); i++) {
				outCookies.put(cookies.get(i).getName(), cookies.get(i).getValue());
			}
			
            String key= null;
            String value= null;
            for (Entry<String, String> entry : set) {
                key= entry.getKey();
                if (key==null || key.isEmpty() || value==null || value.isEmpty()){
                    throw new IllegalArgumentException("cookies key and value both can not be empty");
                }
                BasicClientCookie cookie= new BasicClientCookie(key, value);
                cookie.setDomain(domain);
                cookie.setPath(path);
                cookie.setSecure(useSecure);
                cookieStore.addCookie(cookie);
            }
            return true;
        }
    }

    /**
     * 设置单个Cookie
     * @param key Cookie键
     * @param value Cookie值
     * @param domain 作用域 不可为空
     * @param path 路径 传null默认为"/"
     * @param useSecure 是否使用安全机制 传null 默认为false
     * @return 是否成功设置cookie
     */
    public boolean setCookie(String key, String value, String domain, String path, Boolean useSecure){
        Map<String, String> cookies= new HashMap<String, String>();
        cookies.put(key, value);
        return setCookie(cookies, domain, path, useSecure);
    }

}

 

分享到:
评论

相关推荐

    httpclient 4.5.3完整版jar包.zip

    httpclient4.5.3完整jar包: commons-codec-1.9.jar commons-logging-1.2.jar httpclient-4.5.3.jar httpcore-4.4.6.jar httpmime-4.5.3.jar等等

    httpclient4.5.3 jar完整包含所有依赖包

    HttpClient 4.5.3 (GA) is a maintenance release that fixes a number of defects found since 4.5.2. Please note that as of 4.4 HttpClient requires Java 1.6 or newer. Changelog: ------------------- * ...

    最新httpClient4.5.3所需jar包

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

    httpclient4.5.3所需jar包集合

    本资源提供的"HTTPClient4.5.3所需jar包集合"是针对这个版本的HTTPClient库的所有必要组件的集合,确保你能够完整地使用其功能。 HTTPClient 4.5.3 是一个成熟的HTTP客户端实施库,它支持HTTP/1.1和部分HTTP/2标准...

    HttpClient4.5.3资源

    此资源包"HttpClient4.5.3"提供了HttpClient的版本4.5.3,这是一个稳定且功能丰富的版本,具有诸多改进和修复。 1. **HttpClient 4.5.3 源码分析**: - **模块化设计**:HttpClient 4.5.3采用了模块化设计,使得...

    httpclient-4.5.3中文版文档,很实用

    8. **异步操作**:除了同步API,HttpClient还提供了异步API,基于`Future`接口,可以非阻塞地发送请求并接收响应,适用于高并发场景。 9. **Cookie管理**:HttpClient处理HTTP会话状态,支持标准的Cookie规范,如...

    httpclient-4.5.3.zip

    《HttpClient 4.5.3:构建高效网络通信的核心库》 Apache HttpClient 是一个广泛使用的 Java 库,专为执行HTTP请求而设计。在版本4.5.3中,这个库提供了一系列强大的功能,使开发者能够高效、灵活地处理网络通信...

    httpclient 4.5.3 API doc

    httpclient 4.5.3 API doc httpclient4.5.3.chm 纯网站镜像

    httpclient-4.5.3.zip jar 包

    java jar包,亲测试可用 安全,可以对其进行数字签名,只让能够识别数字签名的用户使用里面的东西。 加快下载速度; 压缩,使文件变小,与ZIP压缩机制完全相同。 ...能够让JAR包里面的文件依赖于统一版本的类文件。...

    httpclient-4.5.3-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.3.jar; 赠送原API文档:httpclient-4.5.3-javadoc.jar; 赠送源代码:httpclient-4.5.3-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.3.pom; 包含翻译后的API文档:httpclient...

    (免费)HttpClient4.5.3及相关依赖包httpcore-4.4.6和httpmime-4.5.3

    总的来说,HttpClient4.5.3、httpcore-4.4.6和httpmime-4.5.3这三者组合,为Java开发者提供了一套全面的HTTP通信解决方案。在处理网络请求时,它们可以帮助开发者实现高效、稳定且灵活的HTTP客户端应用。

    httpclient4.4.1 and httpclient4.5.3.rar

    《HttpClient 4.x:从4.4.1到4.5.3的演进与特性解析》 HttpClient是Apache软件基金会开发的一个Java库,用于在HTTP协议上进行客户端通信。这个库广泛应用于各种网络编程场景,包括数据抓取、API调用、网页登录等。...

    httpclient-4.5.3官方API中文文档_最新译版_2886K

    本文将基于4.5.3版本的HttpClient官方API中文文档,深入探讨其核心概念、使用方法及常见应用场景。 一、HttpClient简介 HttpClient是一款高效的HTTP客户端库,它支持多种HTTP标准,包括HTTP/1.1、HTTP/2以及...

    httpClient4.5.3+Jsoup1.10.2

    httpClient4.5.3+Jsoup1.10.2 commons-codec-1.9.jar commons-logging-1.2.jar httpclient-4.5.3.jar httpcore-4.4.6.jar jsoup-1.10.2.jar

    httpclient-4.5.3.jar

    httpclient-4.5.3.jar Java的工具包,用作web项目采集第三方设备信息开发jar包

    httpclient-4.5.3完整jar包

    httpclient4.5.3完整jar包: commons-codec-1.9.jar commons-logging-1.2.jar httpclient-4.5.3.jar httpcore-4.4.6.jar httpmime-4.5.3.jar等等

    [接近免费]httpClient4.5.3所需jar包

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

    httpclient_4.5.3.jar_httpclient_4.5.3.jar_

    HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持...HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

    httpclient-4.5.3.jar和httpclient-cache-4.5.3.jar 文件

    《HttpClient 4.5.3及其相关库的深入解析》 在Java开发中,HttpClient是一个不可或缺的工具,它为开发者提供了强大的HTTP客户端编程接口。本文将深入探讨标题提及的`httpclient-4.5.3.jar`和`httpclient-cache-...

    httpclient-4.5.3-API文档-中文版.zip

    赠送jar包:httpclient-4.5.3.jar 赠送原API文档:httpclient-4.5.3-javadoc.jar 赠送源代码:httpclient-4.5.3-sources.jar 包含翻译后的API文档:httpclient-4.5.3-javadoc-API文档-中文(简体)版.zip 对应Maven...

Global site tag (gtag.js) - Google Analytics