封装HttpClient工具类;转载请标明出处
来源:互联网 发布:wildfly 端口配置 编辑:程序博客网 时间:2024/05/16 06:30
/** * Created by sunlei on 2016/12/24 0024. */import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.config.CookieSpecs;import org.apache.http.client.config.RequestConfig;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.config.Registry;import org.apache.http.config.RegistryBuilder;import org.apache.http.conn.socket.ConnectionSocketFactory;import org.apache.http.conn.socket.PlainConnectionSocketFactory;import org.apache.http.conn.ssl.NoopHostnameVerifier;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.HttpClients;import org.apache.http.impl.client.LaxRedirectStrategy;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.TrustStrategy;import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;import java.io.IOException;import java.nio.charset.Charset;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import java.util.Map;/** * 封装httpCilent请求,基于httpClient4.5.2开发 * HTTP请求工具类 */public class HttpUtil { private static PoolingHttpClientConnectionManager connectionManager; private static RequestConfig requestConfig; private static final int MAX_TIMEOUT = 5 * 1000; /**----------静态模块加载,主要是设置HttpClient的一些属性----------*/ static { //注册http和https Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", createSSLConnectionSocketFactory()).build(); //设置连接池 connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); //设置连接池大小 connectionManager.setMaxTotal(100); connectionManager.setDefaultMaxPerRoute(100); //(同一个路由允许最大连接数) RequestConfig.Builder configBuilder = RequestConfig.custom(); //设置连接超时 configBuilder.setConnectTimeout(MAX_TIMEOUT); //设置读取超时 configBuilder.setSocketTimeout(MAX_TIMEOUT); //设置从连接池获取连接实例的超时 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT); //此处使用默认的Cookie规范,可以让后续请求共享Cookie configBuilder.setCookieSpec(CookieSpecs.DEFAULT); //支持重定向 configBuilder.setRedirectsEnabled(true); requestConfig = configBuilder.build(); HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setRedirectStrategy(new LaxRedirectStrategy()) .setSSLSocketFactory(createSSLConnectionSocketFactory()) //设置证书// .setProxy(new HttpHost("127.0.0.1",8888)) //设置走代理 方便Fiddler查看抓取请求 .build(); } /** * Get方式请求 * * @param Url */ public static String doGet(String Url) { return doGet(Url, null, null); } /** * Get方式请求 * * @param Url * @param map 请求参数 * @param headers */ public static String doGet(String Url, Map<String, Object> map, Map<String, String> headers) { String html = null; String apiUrl = Url; StringBuffer stringBuffer = new StringBuffer(); int flag = 0; //?标识符 /**----------设置请求参数------------*/ if (map!=null&&map.size() != 0) { for (String mapName : map.keySet()) { if (flag == 0) { stringBuffer.append("?"); } else { stringBuffer.append(mapName).append("=").append(map.get(mapName).toString()); flag++; } } } apiUrl += stringBuffer; HttpGet get = new HttpGet(apiUrl); /**----------设置请求头信息-----------*/ if (headers!=null&&headers.size() != 0) { for (String headerName : headers.keySet()) { get.addHeader(headerName, headers.get(headerName)); } } CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpResponse httpResponse = httpClient.execute(get); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { html = EntityUtils.toString(entity,"utf-8"); } } catch (IOException e) { e.printStackTrace(); } return html; } /** * Post方式请求 * * @param Url * @param map * @param headers */ public static String doPost(String Url, Map<String, Object> map, Map<String, String> headers) { String html = null; String apiUrl = Url; CloseableHttpClient httpClient = HttpClients.createDefault(); try { if (map!=null&&map.size() != 0) { HttpPost post = new HttpPost(apiUrl); List<NameValuePair> list = new ArrayList<NameValuePair>(map.size()); /**----------设置请求参数------------*/ for (Map.Entry<String, Object> entry : map.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); list.add(pair); } /**----------设置请求头信息----------*/ if(headers!=null&&headers.size()!=0) { for (Map.Entry<String, String> entry : headers.entrySet()) { post.addHeader(entry.getKey(),entry.getValue()); } } post.setEntity(new UrlEncodedFormEntity(list, Charset.forName("utf-8"))); HttpResponse httpResponse = httpClient.execute(post); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { html = EntityUtils.toString(entity,"utf-8"); } } } catch(Exception e){ e.printStackTrace(); } return html; } /** * Post方式请求 * * @param Url * @param json * @param json */ public static String doPost(String Url,Object json,Map<String,String> headers){ String html = null; try { HttpPost post = new HttpPost(Url); StringEntity stringEntity = new StringEntity(json.toString(),"utf-8"); stringEntity.setContentType("application/json"); stringEntity.setContentEncoding("utf-8"); post.setEntity(stringEntity); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse httpResponse = httpClient.execute(post); HttpEntity entity = httpResponse.getEntity(); html = EntityUtils.toString(entity,"utf-8"); } catch (Exception e) { e.printStackTrace(); } return html; } /** * 创建SSL连接 * 解决https问题 * */ public static SSLConnectionSocketFactory createSSLConnectionSocketFactory(){ SSLConnectionSocketFactory factory = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return false; } }).build(); factory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); } catch (Exception e) { e.printStackTrace(); } return factory; }}
1 0
- 封装HttpClient工具类;转载请标明出处
- CGridCtrl控件(原文来自vc知识库,转载请标明出处)
- 本文为原创文章,转载请标明出处
- 树状数据库设计方案思考(原创,如需转载请标明出处)
- hacmp学习笔记--请尊重原创 转载时标明出处 谢了
- 怎么在eclipse下进行uiautomator测试用例的调试 (转载请标明出处)
- 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/46596109;
- 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/a137188467/archive/2009/02/03/3859656.aspx
- 转载请注明出处
- 前端面试总结(转载请标明)
- 后端面试总结(转载请标明)
- 为控制台窗口建立消息队列(转载处也没标明出处)
- HttpClient工具类封装
- httpclient封装工具类
- 哈哈,收藏源代码(本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hakule/archive/2008/09/01/2861688.aspx)
- group、grouping、rollup、cube的用法和区别(本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/junmail/archive/2006/12/26/1463132.aspx)
- Nc单据制作单据步骤-- 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/chxzly1981/archive/2007/12/25/1966982.aspx
- 封装的HttpClient工具类
- PackageManager详解
- alloca、malloc、calloc、realloc的详解
- SpringBoot整合Mybatis
- 在VMware10下安装VxWorks6.6虚拟机教程(上篇——准备环节)
- Windows环境下搭建机器学习玩flappy bird(2)
- 封装HttpClient工具类;转载请标明出处
- Python-day3
- C++--模板遇上运算符重载
- 表驱动--用于在复杂消息分发中,取代if/else和switch/case结构
- [LeetCode]445. Add Two Numbers II
- 大数据各组件的开启命令及WEB UI端口号
- 蓝鸥Unity入门Transform学习笔记
- linux单用户模式需要密码登录的安全机制
- 生动形象的jQuery上下文选择器实例