HttpUtils工具类
package net.hs.itn.teng.common.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.URLEncodedUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
/**
* HttpUtils工具类
*
* @author
*
*/
public class HttpUtils {
/**
* 请求方式:post
*/
public static String POST = "post";
/**
* 编码格式:utf-8
*/
private static final String CHARSET_UTF_8 = "UTF-8";
/**
* 报文头部json
*/
private static final String APPLICATION_JSON = "application/json";
/**
* 请求超时时间
*/
private static final int CONNECT_TIMEOUT = 60 * 1000;
/**
* 传输超时时间
*/
private static final int SO_TIMEOUT = 60 * 1000;
/**
* 日志
*/
private static Logger loggger = Logger.getLogger(HttpUtils.class);
/**
*
* @param protocol
* @param url
* @param paraMap
* @return
* @throws Exception
*/
public static String doPost(String protocol, String url,
Map<String, Object> paraMap) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse resp = null;
String rtnValue = null;
try {
if (protocol.equals("http")) {
httpClient = HttpClients.createDefault();
} else {
// 获取https安全客户端
httpClient = HttpUtils.getHttpsClient();
}
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (null != paraMap && paraMap.size() > 0) {
for (Entry<String, Object> entry : paraMap.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry
.getValue().toString()));
}
}
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SO_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
httpPost.setEntity(new UrlEncodedFormEntity(list, CHARSET_UTF_8));
resp = httpClient.execute(httpPost);
rtnValue = EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
} catch (Exception e) {
loggger.error(e.getMessage());
throw e;
} finally {
if (null != resp) {
resp.close();
}
if (null != httpClient) {
httpClient.close();
}
}
return rtnValue;
}
/**
* 获取https,单向验证
*
* @return
* @throws Exception
*/
public static CloseableHttpClient getHttpsClient() throws Exception {
try {
TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
public void checkServerTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
SSLContext sslContext = SSLContext
.getInstance(SSLConnectionSocketFactory.TLS);
sslContext.init(new KeyManager[0], trustManagers,
new SecureRandom());
SSLContext.setDefault(sslContext);
sslContext.init(null, trustManagers, null);
SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClientBuilder clientBuilder = HttpClients.custom()
.setSSLSocketFactory(connectionSocketFactory);
clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
CloseableHttpClient httpClient = clientBuilder.build();
return httpClient;
} catch (Exception e) {
throw new Exception("http client 远程连接失败", e);
}
}
/**
* post请求
*
* @param msgs
* @param url
* @return
* @throws ClientProtocolException
* @throws UnknownHostException
* @throws IOException
*/
public static String post(Map<String, Object> msgs, String url)
throws ClientProtocolException, UnknownHostException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost request = new HttpPost(url);
List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
if (null != msgs) {
for (Entry<String, Object> entry : msgs.entrySet()) {
if (entry.getValue() != null) {
valuePairs.add(new BasicNameValuePair(entry.getKey(),
entry.getValue().toString()));
}
}
}
request.setEntity(new UrlEncodedFormEntity(valuePairs, CHARSET_UTF_8));
CloseableHttpResponse resp = httpClient.execute(request);
return EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
} finally {
httpClient.close();
}
}
/**
* get请求
*
* @param msgs
* @param url
* @return
* @throws ClientProtocolException
* @throws UnknownHostException
* @throws IOException
*/
public static String get(Map<String, Object> msgs, String url)
throws ClientProtocolException, UnknownHostException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
if (null != msgs) {
for (Entry<String, Object> entry : msgs.entrySet()) {
if (entry.getValue() != null) {
valuePairs.add(new BasicNameValuePair(entry.getKey(),
entry.getValue().toString()));
}
}
}
// EntityUtils.toString(new UrlEncodedFormEntity(valuePairs),
// CHARSET);
url = url + "?" + URLEncodedUtils.format(valuePairs, CHARSET_UTF_8);
HttpGet request = new HttpGet(url);
CloseableHttpResponse resp = httpClient.execute(request);
return EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
} finally {
httpClient.close();
}
}
public static <T> T post(Map<String, Object> msgs, String url,
Class<T> clazz) throws ClientProtocolException,
UnknownHostException, IOException {
String json = HttpUtils.post(msgs, url);
T t = JSON.parseObject(json, clazz);
return t;
}
public static <T> T get(Map<String, Object> msgs, String url, Class<T> clazz)
throws ClientProtocolException, UnknownHostException, IOException {
String json = HttpUtils.get(msgs, url);
T t = JSON.parseObject(json, clazz);
return t;
}
public static String postWithJson(Map<String, Object> msgs, String url)
throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
String jsonParam = JSON.toJSONString(msgs);
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", APPLICATION_JSON);
post.setEntity(new StringEntity(jsonParam, CHARSET_UTF_8));
CloseableHttpResponse response = httpClient.execute(post);
return new String(EntityUtils.toString(response.getEntity()).getBytes("iso8859-1"),CHARSET_UTF_8);
} finally {
httpClient.close();
}
}
public static <T> T postWithJson(Map<String, Object> msgs, String url,
Class<T> clazz) throws ClientProtocolException,
UnknownHostException, IOException {
String json = HttpUtils.postWithJson(msgs, url);
T t = JSON.parseObject(json, clazz);
return t;
}
}
HttpUtils工具类的更多相关文章
- 调用http接口的工具类
网上面有很多,但是我们项目怎么也调不到结果,试了差不多很多案例,都是报connection reset 后来,我发现是有一个验证,需要跳过验证.然后才能调接口.所以找了一个忽略https的方法.进行改 ...
- HttpUtils 用于进行网络请求的工具类
原文:http://www.open-open.com/code/view/1437537162631 import java.io.BufferedReader; import java.io.By ...
- java工具类
1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...
- Android开发常用工具类
来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...
- 53. Android常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...
- utils部分--一些通用的工具类封装
1.简介 utils部分是对一些常用的工具类进行简单的封装,使用起来比较方便.这里列举常用的一些. 2.ContextUtils使用 主要封装了网络判断.一些方法解释如下: ? 1 2 3 4 5 6 ...
- Android快速开发系列 10个常用工具类
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...
- Android常用的工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils. Prefe ...
- android 开发 常用工具类
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...
随机推荐
- [转]Maven2中snapshot快照库的使用
Post by 铁木箱子 in Java, 技术杂谈 on 2011-10-28 12:12. [转载声明] 转载时必须标注:本文来源于铁木箱子的博客http://www.mzone.cc[原文地址] ...
- 循环杀死Mysql sleep进程脚本
#!/bin/sh while : do n=`mysqladmin processlist -uadmin -p***|grep -i sleep |wc -l` date=`date +%Y%m% ...
- SlidingMenu官方实例分析3——PropertiesActivity
PropertiesActivity此类主要是对SlidingMenu设置的一些展示,也是为了使用者能快速的掌握SlidingMenu 的特点. 首先获得SlidingMenu对象: SlidingM ...
- SSH总结(一)
其实学习struts等框架,不仅要知道怎么用,我们还应该多去看看框架的源码,知道为什么可以这样使用,凡事都知道为什么,以这样的态度学习,我们才能更加深一步的理解原理好实现方式,本类博客主要是个人学习总 ...
- C++ 矩阵计算库 :Eigen库
Eigen http://eigen.tuxfamily.org/index.php?title=Main_Page 下载http://bitbucket.org/eigen/eigen/get/3. ...
- ios 集成阿里百川的坑-【SDK初始化-iOS】读取身份图片AppKey失败
最简易方法调用淘宝app: 引用文件 #import <AlibcTradeSDK/AlibcTradeSDK.h> AlibcWebViewController* view = [[Al ...
- Laravel5.1 模型 --一对一关系
这篇文章主要记录模型的一对一关系,关联关系是Model的一种非常方便的功能. 1 实现一对一关系 1.1 准备工作 首先我们需要创建两张表和对应的两个模型,第一个模型是用户表,第二个模型是账号表. 这 ...
- Collection Set List 集合二
Set List 都继承Collection Collection:元素之间没有顺序,允许重复和多个null元素对象. Set:元素之间没有顺序,不允许重复只能存一个null. List:元素之间有顺 ...
- 网页或WEB应用或PC端浏览器调用百度地图API
今天在写微网页中遇见了调用百度地图这个问题:在一个容器中显示地图信息如图(设计图截图) 然后在网上查了接口:http://api.map.baidu.com/,就是这个东东,当然不止这个,还有几个必选 ...
- jmeter操作myql数据库
1.先安装mysql的驱动mysql-connector-java-5.1.7-bin.jar 配置jdbc的connection configuration Database Url :jdbc:m ...