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. js 简单的样式封装

    <script> function test(value){ var str=value; document.write("<div style=\"width: ...

  2. java 窗体

    import javax.swing.*; /** * 一个简单的java窗体例子 */ public class Test { public static void main(String[] ar ...

  3. IOS 键盘协议之中的一个 &lt;UITextFieldDelegate&gt;

    1. 设置键盘的第一响应者后,便可通过点击TextField唤出键盘 设置键盘第一响应者方法为: [textField becomeFirstResponder];//此时,textField 输入框 ...

  4. js创建对象的最佳方式

    1.对象的定义 ECMAScript中,对象是一个无序属性集,这里的“属性”可以是基本值.对象或者函数 2.数据属性与访问器属性 数据属性即有值的属性,可以设置属性只读.不可删除.不可枚举等等 访问器 ...

  5. Achartengine.jar绘制动态图形-饼图

    Achartengine.jar绘制动态图形一 --饼图 PS:我们在做安卓程序的时候,免不了会做一些图形,自己可以选择自定义view ,就是用Canvas画,也可以用写好的jar包,就是achart ...

  6. XML 文档的结构

    XML 文档的组成 一个XML文档由两部分构成:第一部分是文档序言,第二部分是文档元素(节点). 1.文档序言 文档序言通常位于XML文档的顶端,根元素之前出现,它是一个特定的包含XML 文档设定信息 ...

  7. D3D9和OpenGL加载纹理图片的API是哪个?

    D3D9 创建一个空纹理,当返回 S_OK 且 ppTexture 纹理对象指针不为 NULL 时,则表示该函数调用成功. HRESULT D3DXCreateTexture( _In_  LPDIR ...

  8. ES6学习笔记(三)——数值的扩展

    看到这条条目录有没有感觉很枯燥,觉得自己的工作中还用不到它所以实在没有耐心看下去,我也是最近得闲,逼自己静下心来去学习去总结,只有在别人浮躁的时候你能静下心来去学去看去总结,你才能进步.毕竟作为前端不 ...

  9. Mysql 命令详解

    1.读取服务器变量:    show [global|session] variables;2.更改非静态(只读)变量:    set [global|session] <variable_na ...

  10. windows server2003/2008中权限账户

    在windows server 2003与windows server 2008 R2中,查看文件夹权限时,尤其是用cacls命令查看时,经常会见nt authority system这样的用户信息. ...