package net.csdn.blog.chaijunkun.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
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.SSLContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.utils.URIBuilder;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.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.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BestMatchSpec;
import org.apache.http.message.BasicNameValuePair;
class AnyTrustStrategy implements TrustStrategy{
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}
public class HttpUtil {
private static final Log log= LogFactory.getLog(HttpUtil.class);
private static int bufferSize= 1024;
private static volatile HttpUtil instance;
private ConnectionConfig connConfig;
private SocketConfig socketConfig;
private ConnectionSocketFactory plainSF;
private KeyStore trustStore;
private SSLContext sslContext;
private LayeredConnectionSocketFactory sslSF;
private Registry<ConnectionSocketFactory> registry;
private PoolingHttpClientConnectionManager connManager;
private volatile HttpClient 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 HttpUtil(){
//设置连接参数
connConfig = ConnectionConfig.custom().setCharset(Charset.forName(defaultEncoding)).build();
socketConfig = SocketConfig.custom().setSoTimeout(100000).build();
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF);
//指定信任密钥存储对象和连接套接字工厂
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
registry = registryBuilder.build();
//设置连接管理器
connManager = new PoolingHttpClientConnectionManager(registry);
connManager.setDefaultConnectionConfig(connConfig);
connManager.setDefaultSocketConfig(socketConfig);
//指定cookie存储对象
cookieStore = new BasicCookieStore();
//构建客户端
client= HttpClientBuilder.create().setDefaultCookieStore(cookieStore).setConnectionManager(connManager).build();
}
public static HttpUtil getInstance(){
synchronized (HttpUtil.class) {
if (HttpUtil.instance == null){
instance = new HttpUtil();
}
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 HttpUtil.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 HttpUtil.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(HttpUtil.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 HttpUtil.readStream(this.doPostForStream(url, queryParams), null);
}
public InputStream doPostForStream(String url, Map<String,
没有合适的资源?快使用搜索试试~ 我知道了~
基于HttpClient 4.3的可访问自签名HTTPS站点的新版工具类
共3个文件
java:2个
xml:1个
5星 · 超过95%的资源 需积分: 43 1.3k 下载量 97 浏览量
2014-10-16
18:54:15
上传
评论 8
收藏 7KB ZIP 举报
温馨提示
HttpClient在当今Java应用中的位置越来越重要。从该项目的变迁过程我们不难发现,其已经从apache-commons众多的子项目中剥离,一跃成为如今的顶级项目,可见它的分量。然而随着项目的升级和架构的调整,很多以前常用的类和方法都已被打上了@Deprecated注解,作为一个有代码洁癖的程序猿,我们也有必要升级一下工具类,让代码更加整洁。 另外在项目中正好需要访问https协议的接口,而对应的服务器没有购买商业CA颁发的正式受信证书,只是做了个自签名(联想一下12306网站购票时提示的那个警告信息),默认情况下通过HttpClient访问会抛出异常。相关文章参阅:http://blog.csdn.net/chaijunkun/article/details/40145685
资源推荐
资源详情
资源评论
收起资源包目录
http-client-util.zip (3个子文件)
src
test
java
net
csdn
blog
chaijunkun
util
AppTest.java 592B
main
java
net
csdn
blog
chaijunkun
util
HttpUtil.java 13KB
pom.xml 1KB
共 3 条
- 1
Jack_Chai
- 粉丝: 563
- 资源: 26
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
- 3
- 4
- 5
- 6
前往页