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,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...
随机推荐
- Linux 实用工具vi
vi有输入和命令两种工作模式.命令模式是用来运行一些编排文件.存档以及离开vi等操作命令. 当执行vi后,首先进入命令模式,此时输入的人数字符都被视为命令. 在命令模式下,可以使用如下两个键进入文本输 ...
- 集合Map多对多映射(使用xml文件)
我们可以使用set,bag,map等来映射多对多关系.在这里,我们将使用map来进行多对多映射. 在这种情况下,将创建三个表. 多对多映射示例 我们需要创建以下文件来映射map元素.首先创建一个项目: ...
- 项目实战:JSP应用开发_接口:接口的实现
在类的声明中使用implements关键字来实现接口,一个类可以同时实现多个接口,各接口间用“,”隔开. class classname implements interfacename{ //重 ...
- python使用电子邮件模块smtplib的方法(发送图片 附件)实用可行
Smptp类定义:smtplib.SMTP(host[,port[,local_hostname[,,timeout]]]),作为SMTP的构造函数,功能是与smtp服务器建立连接,在连接成功后,就可 ...
- 【BZOJ2320】最多重复子串 调和级数+hash
[BZOJ2320]最多重复子串 Description 一个字符串P的重复数定义为最大的整数R,使得P可以分为R段连续且相同的子串.比方说,“ababab”的重复数为3,“ababa”的重复数为1. ...
- CSS伪类选择器active模拟JavaScript点击事件
一.说明 设置元素在被用户激活(在鼠标点击与释放之间发生的事件)时的样式. IE7及更早浏览器只支持a元素的:active,从IE8开始支持其它元素的:active. 另:如果需要给超链接定义:访问前 ...
- Linux Debian 如何部署 Qt?
Linux Debian 如何部署 Qt? 在这里以 HelloWorld 为例 目录结构如下: . ├── HelloWorld ├── HelloWorld.sh ├── imageformats ...
- [BZOJ3551]Peaks
[BZOJ3551]Peaks BZOJ luogu 建Kruskal重构树,点权为边权 按dfn序建出主席树 倍增找到能跳到的最浅的祖先 主席树查询一下 #include<bits/stdc+ ...
- Spring Boot在aop中获取request对象
doBefore(){ ServetRequestAttrbtes attributes = (ServetRequestAttrbtes)RequestContextHolder.getHttpat ...
- 使用Kotlin开发Android应用 - 环境搭建 (1)
一. 在Android Studio上安装Kotlin插件 按快捷键Command+, -> 在Preferences界面找到Plugins -> 点击Browse repositorie ...