httpclient 支持代理和http & https
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<String,String> 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<String, String> 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<NameValuePair> 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<NameValuePair> params = new ArrayList<NameValuePair>();
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<String, String> map = new HashMap<String, String>();
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, ",") + "]");
} }
httpclient 支持代理和http & https的更多相关文章
- android httpClient 支持HTTPS的2种处理方式
摘自: http://www.kankanews.com/ICkengine/archives/9634.shtml 项目中Android https或http请求地址重定向为HTTPS的地址,相信很 ...
- Confluence 6 代理和 HTTPS 设置连接器
很多用户选择将 Confluence 运行在反向代理的后面,同时还启用了 HTTPS.将你的的 Confluence 反向代理配置正确就显得非常必要了,并且能够避免后期在使用 Confluence 遇 ...
- jdk动态代理和cglib动态代理底层实现原理详细解析(cglib动态代理篇)
代理模式是一种很常见的模式,本文主要分析cglib动态代理的过程 1. 举例 使用cglib代理需要引入两个包,maven的话包引入如下 <!-- https://mvnrepository.c ...
- Android 使Volley完美支持自定义证书的Https
其实在最早的版本里,Volley甚至是不支持https协议的,只能跑http,当然你也可以自己修改他的源码让他支持,如今volley的代码经过一些改进以后, 已经可以完美支持https协议了,无论是在 ...
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。
基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别. 我还是喜欢基于Schema风格的Spring事务管理,但也有很多人在用基于@Tras ...
- Spring -- <tx:annotation-driven>注解基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)的区别。
借鉴:http://jinnianshilongnian.iteye.com/blog/1508018 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional ...
- 使Volley完美支持自定义证书的Https
其实在最早的版本里,Volley甚至是不支持https协议的,只能跑http,当然你也可以自己修改他的源码让他支持,如今volley的代码经过一些改进以后, 已经可以完美支持https协议了,无论是在 ...
- 使用Nginx反向代理和proxy_cache缓存搭建CDN服务器加快Web访问速度
碰到问题:移动用户访问web服务器www.osyunwei.com很慢解决办法:1.在移动机房放置一台nginx反向代理服务器2.通过域名DNS智能解析,所有移动用户访问www.osyunwei.co ...
- spring 如何决定使用jdk动态代理和cglib(转)
Spring1.2: 将事务代理工厂[TransactionProxyFactoryBean] 或 自动代理拦截器[BeanNameAutoProxyCreator] 的 proxyTargetCla ...
随机推荐
- DAY2 raw_input() 与 input() Python
使用input和raw_input都可以读取控制台的输入,input()只能接受int,float或由它们组成的表达式: Python 2.7.5 (default, Mar 19 2014, 07: ...
- Android内存性能优化(内部资料总结) eoe转载
刚入门的童鞋肯能都会有一个疑问,Java不是有虚拟机了么,内存会自动化管理,我们就不必要手动的释放资源了,反正系统会给我们完成.其实Java中没有指针的概念,但是指针的使用方式依然存在,一味的依赖系统 ...
- 小米手机无法打开程序报错Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication的解决办法
打开studio的setting 然后 Preferences -> Build, Execution, Deployment -> Instant Run -> Enable In ...
- ClearCanvas DICOM 开发系列 一
概述 C#开源的DICOM server.支持影像处理.影像归档.影像管理.影像传输和影像浏览功能.开源代码可学习地方很多. 官方网站:http://www.clearcanvas.ca buildi ...
- iframe自适应宽度
<iframe id="course_content" style="width:100%;margin:5px 0 0;" scrolling=&quo ...
- angular.js初探
2015年7月27日 22:26:35 星期一 用在我论坛里的小栗子: 先列出来一级回帖, 点击帖子前边的"查看回复"按钮无刷新的去请求该帖子的所有回复 首先要引用js文件, 我这 ...
- ACM/ICPC 之 平面几何-两直线关系(POJ 1269)
题意:给定四点的坐标(x,y),分别确定两直线,求出其交点,若重合or平行则输出相应信息 用四个点的坐标算出直线通式(ax+by+c=0)中的a,b,c,然后利用a,b,c计算出交点坐标(其他公式不够 ...
- We7 CMS研究
我下载的we7 3.0是基于vs 2010的,官方网站也建议使用vs2010,但是我有追新的习惯,并相信vs 2013一定能够兼容vs2010的项目,于是在vs2013下打开解决方案并且全部升级,把目 ...
- effective OC2.0 52阅读笔记(三 接口与API设计)
第三章:接口与API设计 15 用前缀避免命名空间冲突 总结:避免重名符号错误的唯一办法是变相实现命名空间.为所有符号都加上命名前缀.类和分类都应加三字前缀.注意类实现文件中的纯C函数及全局变量,是算 ...
- 9.SpringMVC和json结合传递数据 && 10.SpringMVC获取controller中json的数据