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工具类的更多相关文章

  1. 调用http接口的工具类

    网上面有很多,但是我们项目怎么也调不到结果,试了差不多很多案例,都是报connection reset 后来,我发现是有一个验证,需要跳过验证.然后才能调接口.所以找了一个忽略https的方法.进行改 ...

  2. HttpUtils 用于进行网络请求的工具类

    原文:http://www.open-open.com/code/view/1437537162631 import java.io.BufferedReader; import java.io.By ...

  3. java工具类

    1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...

  4. Android开发常用工具类

    来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...

  5. 53. Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...

  6. utils部分--一些通用的工具类封装

    1.简介 utils部分是对一些常用的工具类进行简单的封装,使用起来比较方便.这里列举常用的一些. 2.ContextUtils使用 主要封装了网络判断.一些方法解释如下: ? 1 2 3 4 5 6 ...

  7. Android快速开发系列 10个常用工具类

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...

  8. Android常用的工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils. Prefe ...

  9. android 开发 常用工具类

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...

随机推荐

  1. WPF绑定Binding及模式

    绑定,就是把一个对象属性的值绑定在别的对象的属性上 1. 默认绑定 public class Company { public string Name { get; set; } } XAML代码 1 ...

  2. SlidingMenu官方实例分析8——CustomAnimation

    CustomAnimation 构造方法: 其中CanvasTransformer对象是重点,因为他是实现动画的对象,设置对象的代码如下: 其中变化方法如下: 其中的canvas.scale(),方法 ...

  3. Python中的多进程与多线程/分布式该如何使用

    在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global interpreter lock(也被亲切的称为“GIL”)指指点点,说它阻碍了Python的多线程程序同时 ...

  4. django 1.10以上版本,引入js

    引入js库 建立static文件夹:  注意上图里面static文件夹的路径,再在里面添加js文件夹,js文件夹里面就可以放我们需要的js文件了. 配置相关文件 接下来,想要使用这些js我们还需要进行 ...

  5. Mongo同步数据到Elasticsearch

    个人博客:https://blog.sharedata.info/ 最近需要把数据从Mongo同步到Elasticsearch环境:centos6.5python2.7pipmongo-connect ...

  6. Java 基础巩固:装箱拆箱 你真的熟悉吗

    先考两道题: Integer a1 = 300; Integer a2 =300; System.out.print(a1 == a2); Integer b1 = 1; Integer b2 = 1 ...

  7. sql server数据库创建、删除,创建表,数据库的sql语句

    create database test on primary -- 默认就属于primary文件组,可省略(/*--数据文件的具体描述--*/ name='test', -- 主数据文件的逻辑名称 ...

  8. Spring基础知识详解

    Spring 概述 1. 什么是spring? Spring 是个java企业级应用的开源开发框架.Spring主要用来开发Java应用,但是有些扩展是针对构建J2EE平台的web应用.Spring ...

  9. influxDB 变换类函数

    1.DERIVATIVE()函数 作用:返回一个字段在一个series中的变化率. InfluxDB会计算按照时间进行排序的字段值之间的差异,并将这些结果转化为单位变化率.其中,单位可以指定,默认为1 ...

  10. python的文件处理学习笔记

    python的文件处理函数是open() 以下主要是关于这个函数的一些学习笔记 1.文件处理离不开编码 要注意的是文件打开时的编码和文件保存时的编码的统一,这样才能保证你打开的文件不会存在乱码 总结: ...