博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
httpclient 支持代理和http & https
阅读量:6554 次
发布时间:2019-06-24

本文共 11345 字,大约阅读时间需要 37 分钟。

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.net.URI;import java.security.KeyStore;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 javax.net.ssl.SSLContext;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.auth.AuthScope;import org.apache.http.auth.Credentials;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;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.utils.URIBuilder;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContexts;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;/** * @author sprinng * @Description jdk >=1.7 兼容http https * */public class HttpUtils {    private static CloseableHttpClient httpClientBuilder=null;        /**     *    http 和 https      * @param useProxy 是否使用代理     * @param needCert 是否需要证书     * @return     */    private static CloseableHttpClient createSSLClientDefault(boolean useProxy,boolean needCert) {        SSLConnectionSocketFactory sslsf = null;        try {            if(needCert){                InputStream instream = new FileInputStream(new File("D:/cert/client.p12"));                InputStream instream1 = new FileInputStream(new File("D:/cert/tbb.jks"));                KeyStore keyStore = KeyStore.getInstance("PKCS12");                KeyStore trustStore = KeyStore.getInstance("JKS");                try {                    //设置客户端证书                    keyStore.load(instream, "12345678".toCharArray());                    //设置服务器证书                    trustStore.load(instream1, "12345678".toCharArray());                } catch (Exception e) {                    ECommonUtil.getLog().error("导入证书错误" + e);                } finally {                    if (instream != null) {                        instream.close();                    }                    if (instream1 != null) {                        instream1.close();                    }                }                SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).loadKeyMaterial(keyStore, "12345678".toCharArray()).build();                sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);            }else{                SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {                    @Override                    public boolean isTrusted(X509Certificate[] chain, String authType)                            throws CertificateException {                        return true;                    }                }).build();                sslsf = new SSLConnectionSocketFactory(sslContext,new String []{"TLSv1.2"}, null,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);            }            if(useProxy){                CredentialsProvider credsProvider = new BasicCredentialsProvider();                AuthScope authScope = new AuthScope(PropertiesUtil.properties.getProperty("proxy_host"),Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")));                Credentials credentials = new  UsernamePasswordCredentials(PropertiesUtil.properties.getProperty("proxy_user"), PropertiesUtil.properties.getProperty("proxy_password"));                credsProvider.setCredentials(authScope, credentials);                httpClientBuilder= HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credsProvider).build();            }else{                httpClientBuilder= HttpClients.custom().setSSLSocketFactory(sslsf).build();            }            return httpClientBuilder;        } catch (Exception e) {            ECommonUtil.getLog().error("创建https导入证书错误"+e);        }        return HttpClients.createDefault();    }    /**     *      * @param url 请求地址     * @param map 请求参数      * @param res 返回结果     * @param timeOut 超时时间(min)     * @param useProxy 是否使用代理     * @return     * @throws Exception     */    public static String get(String url,Map
map, String res, int timeOut, boolean useProxy, boolean needCert) throws Exception{ RequestConfig config = null; CloseableHttpClient httpClient=null; CloseableHttpResponse response=null; if(httpClientBuilder==null){ httpClient= HttpUtils.createSSLClientDefault(useProxy,needCert); }else{ httpClient=httpClientBuilder; } URIBuilder uriBuilder=new URIBuilder(url); for (Entry
entry : map.entrySet()) { uriBuilder=uriBuilder.setParameter(entry.getKey(),entry.getValue()); } URI uri=uriBuilder.build(); HttpGet httpGet=new HttpGet(uri); try { if(useProxy){ HttpHost proxy = new HttpHost(PropertiesUtil.properties.getProperty("proxy_host"), Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")),"http"); config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(timeOut * 1000 * 60).build(); }else{ config = RequestConfig.custom().setConnectTimeout(timeOut * 1000 * 60).build(); } httpGet.setConfig(config); ECommonUtil.getLog().info("执行get请求" + httpGet.getRequestLine()); response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { ECommonUtil.getLog().info("响应状态:"+ response.getStatusLine()); String rStr=EntityUtils.toString(entity,"UTF-8"); ECommonUtil.getLog().info("响应内容:" + rStr); if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){ res=rStr; } EntityUtils.consume(entity); } }catch (Exception e) { ECommonUtil.getLog().info("http请求错误"+e); throw e; }finally{ if(httpGet!=null){ httpGet.releaseConnection(); } if(response!=null){ response.close(); } if(httpClient!=null){ httpClient.close(); } } return res; } /** * * @param url 请求地址 * @param params 请求参数 * @param res 返回结果 * @param timeOut 超时时间(min) * @param useProxy 是否使用代理 * @param needCert 是否使用证书 * @return * @throws Exception */ @SuppressWarnings({ "deprecation", "unused" }) private static String post(String url, List
params, String res, int timeOut, boolean useProxy, boolean needCert) throws Exception { RequestConfig config = null;CloseableHttpClient httpClient=null; CloseableHttpResponse response=null; if(httpClientBuilder==null){ httpClient= HttpUtils.createSSLClientDefault(useProxy,needCert); }else{ httpClient=httpClientBuilder; } HttpPost httpPost = new HttpPost(url); if(useProxy){ HttpHost proxy = new HttpHost(PropertiesUtil.properties.getProperty("proxy_host"), Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")),"http"); config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(timeOut * 1000 * 60).build(); }else{ config = RequestConfig.custom().setConnectTimeout(timeOut * 1000 * 60).build(); } httpPost.setConfig(config); // 设置类型 httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); try { response = httpClient.execute(httpPost); if(302 == response.getStatusLine().getStatusCode()){ ECommonUtil.getLog().info(response.getLastHeader("Location").getValue()); post(response.getLastHeader("Location").getValue(), params, res, timeOut, useProxy,needCert); } HttpEntity entity = response.getEntity(); res = EntityUtils.toString(entity, "UTF-8"); ECommonUtil.getLog().info(res); EntityUtils.consume(entity); } catch (IOException e) { ECommonUtil.getLog().info("请求异常"+e); e.printStackTrace(); } finally { if (response != null) { response.close(); } if (httpPost != null) { httpPost.releaseConnection(); } if (httpClient != null) { httpClient.close(); } } return res; } public static void main(String[] args) throws Exception { //-----------post---------------- List
params = new ArrayList
(); params.add(new BasicNameValuePair("req", "{\"method\":\"checkMobile\",\"timestamp\":\"A100000000000001\",\"channelCode\":\"A1\",\"queryType\":\"1\",\"telephone\":\"15301929770\"}"));// HttpUtilsDemo.post("http://www.baidu.com", params,"",5,true);// HttpUtilsDemo.post("https://localhost/spdbSjptServer/service.cgi", params, "" , 5 ,false);// HttpUtilsDemo.post("http://localhost:7070/spdbSjptServer/service.cgi", params, "" , 5 ,false); //-----------get------------------ String method = "{\"method\":\"checkMobile\",\"timestamp\":\"A100000000000001\",\"channelCode\":\"A1\",\"queryType\":\"1\",\"telephone\":\"15301929770\"}"; Map
map = new HashMap
(); map.put("req", method);// HttpUtilsDemo.get("https://localhost/spdbSjptServer/service.cgi", map,"",5,false); HttpUtils.get("http://localhost:7070/spdbSjptServer/service.cgi", map, "", 5, false,false);// HttpUtilsDemo.get("https://localhost/spdbSjptServer/service.cgi", map, "", 5, false,true);// HttpUtilsDemo.get("http://www.baidu.com", map, "", 5, true,false); } }
import java.io.IOException;import java.util.Properties;public class PropertiesUtil {    public static final Properties properties = new Properties();    static {         try {          properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("config.properties"));         } catch (IOException e) {              ECommonUtil.getLog().error("初始config配置文件失败");        }    }}
import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;public class ECommonUtil {    private static  Logger LOG = Logger.getLogger(ECommonUtil.class);    public static Logger getLog() {        return LOG;    }        public static void printSQL(String sql, Object... params) {        getLog().info("SQL: " + sql);        getLog().info("PARAMS: [" + StringUtils.join(params, ",") + "]");    }    }

 

转载地址:http://nknco.baihongyu.com/

你可能感兴趣的文章
遭遇sql server 2005 启动包未能正确加载需要重新安装错误,重装.NET FRAMEWORK经历分析...
查看>>
OAF_VO系列3 - Binding Style绑定方式
查看>>
《Essential C++》读书笔记 之 基于对象编程风格
查看>>
Sublime Text2 常用快捷键
查看>>
ASP.NET MVC上传文件----uploadify的使用
查看>>
VirtualBox创建虚拟电脑、执行Genymotion模拟器报错
查看>>
新生儿操作系统操作手册
查看>>
linux下如何安装charles
查看>>
正在载入数据中效果
查看>>
Js模型和封装
查看>>
第二章 Java浮点数精确计算
查看>>
apiCloud实现加载更多效果,基本完美~
查看>>
Redis基准
查看>>
如何使用openssl生成RSA公钥和私钥对
查看>>
当我们安装使用时,会出现eclipse启动不了,出现“Java was started but returned exit code=13......”的问题...
查看>>
2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)
查看>>
简明 MongoDB 入门教程
查看>>
.NET Core 3.0中的数据库驱动框架System.Data
查看>>
北大AI公开课2019 | 雷鸣:人工智能革命与机遇
查看>>
英特尔开源计算机视觉数据标签工具CVAT,加速数据注释
查看>>