Http和Https网络同步请求httpclient和异步请求async-http-client
原文:https://blog.csdn.net/fengshizty/article/details/53100694
Http和https网络请求
主要总结一下使用到的网络请求框架,一种是同步网络请求org.apache.httpcomponents的httpclient,另一种是异步网络请求com.ning的async-http-client,总结一下常用的http请求方式封装使用,如post、get、put、delete等,以及涉及到ssl证书https请求的双向证书验证。
一、apache同步请求httpclient
1、引入文件
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.5.2</version>
- </dependency>
2、http和https的方法封装
涉及常用的post和get的请求,https的ssl双向证书验证。
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.security.KeyStore;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import javax.net.ssl.SSLContext;
- import org.apache.http.NameValuePair;
- 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.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.message.BasicNameValuePair;
- import org.apache.http.ssl.SSLContexts;
- import org.apache.http.util.EntityUtils;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- /**
- * 创建时间:2016年11月9日 下午4:16:32
- *
- * @author andy
- * @version 2.2
- */
- public class HttpUtils {
- private static final String DEFAULT_CHARSET = "UTF-8";
- private static final int CONNECT_TIME_OUT = 5000; //链接超时时间3秒
- private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom().setConnectTimeout(CONNECT_TIME_OUT).build();
- private static SSLContext wx_ssl_context = null; //微信支付ssl证书
- static{
- Resource resource = new ClassPathResource("wx_apiclient_cert.p12");
- try {
- KeyStore keystore = KeyStore.getInstance("PKCS12");
- char[] keyPassword = ConfigUtil.getProperty("wx.mchid").toCharArray(); //证书密码
- keystore.load(resource.getInputStream(), keyPassword);
- wx_ssl_context = SSLContexts.custom().loadKeyMaterial(keystore, keyPassword).build();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * @description 功能描述: get 请求
- * @param url 请求地址
- * @param params 参数
- * @param headers headers参数
- * @return 请求失败返回null
- */
- public static String get(String url, Map<String, String> params, Map<String, String> headers) {
- CloseableHttpClient httpClient = null;
- if (params != null && !params.isEmpty()) {
- StringBuffer param = new StringBuffer();
- boolean flag = true; // 是否开始
- for (Entry<String, String> entry : params.entrySet()) {
- if (flag) {
- param.append("?");
- flag = false;
- } else {
- param.append("&");
- }
- param.append(entry.getKey()).append("=");
- try {
- param.append(URLEncoder.encode(entry.getValue(), DEFAULT_CHARSET));
- } catch (UnsupportedEncodingException e) {
- //编码失败
- }
- }
- url += param.toString();
- }
- String body = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.custom()
- .setDefaultRequestConfig(REQUEST_CONFIG)
- .build();
- HttpGet httpGet = new HttpGet(url);
- response = httpClient.execute(httpGet);
- body = EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return body;
- }
- /**
- * @description 功能描述: get 请求
- * @param url 请求地址
- * @return 请求失败返回null
- */
- public static String get(String url) {
- return get(url, null);
- }
- /**
- * @description 功能描述: get 请求
- * @param url 请求地址
- * @param params 参数
- * @return 请求失败返回null
- */
- public static String get(String url, Map<String, String> params) {
- return get(url, params, null);
- }
- /**
- * @description 功能描述: post 请求
- * @param url 请求地址
- * @param params 参数
- * @return 请求失败返回null
- */
- public static String post(String url, Map<String, String> params) {
- CloseableHttpClient httpClient = null;
- HttpPost httpPost = new HttpPost(url);
- List<NameValuePair> nameValuePairs = new ArrayList<>();
- if (params != null && !params.isEmpty()) {
- for (Entry<String, String> entry : params.entrySet()) {
- nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
- }
- }
- String body = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.custom()
- .setDefaultRequestConfig(REQUEST_CONFIG)
- .build();
- httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET));
- response = httpClient.execute(httpPost);
- body = EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return body;
- }
- /**
- * @description 功能描述: post 请求
- * @param url 请求地址
- * @param s 参数xml
- * @return 请求失败返回null
- */
- public static String post(String url, String s) {
- CloseableHttpClient httpClient = null;
- HttpPost httpPost = new HttpPost(url);
- String body = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.custom()
- .setDefaultRequestConfig(REQUEST_CONFIG)
- .build();
- httpPost.setEntity(new StringEntity(s, DEFAULT_CHARSET));
- response = httpClient.execute(httpPost);
- body = EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return body;
- }
- /**
- * @description 功能描述: post https请求,服务器双向证书验证
- * @param url 请求地址
- * @param params 参数
- * @return 请求失败返回null
- */
- public static String posts(String url, Map<String, String> params) {
- CloseableHttpClient httpClient = null;
- HttpPost httpPost = new HttpPost(url);
- List<NameValuePair> nameValuePairs = new ArrayList<>();
- if (params != null && !params.isEmpty()) {
- for (Entry<String, String> entry : params.entrySet()) {
- nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
- }
- }
- String body = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.custom()
- .setDefaultRequestConfig(REQUEST_CONFIG)
- .setSSLSocketFactory(getSSLConnectionSocket())
- .build();
- httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET));
- response = httpClient.execute(httpPost);
- body = EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return body;
- }
- /**
- * @description 功能描述: post https请求,服务器双向证书验证
- * @param url 请求地址
- * @param s 参数xml
- * @return 请求失败返回null
- */
- public static String posts(String url, String s) {
- CloseableHttpClient httpClient = null;
- HttpPost httpPost = new HttpPost(url);
- String body = null;
- CloseableHttpResponse response = null;
- try {
- httpClient = HttpClients.custom()
- .setDefaultRequestConfig(REQUEST_CONFIG)
- .setSSLSocketFactory(getSSLConnectionSocket())
- .build();
- httpPost.setEntity(new StringEntity(s, DEFAULT_CHARSET));
- response = httpClient.execute(httpPost);
- body = EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return body;
- }
- //获取ssl connection链接
- private static SSLConnectionSocketFactory getSSLConnectionSocket() {
- return new SSLConnectionSocketFactory(wx_ssl_context, new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}, null,
- SSLConnectionSocketFactory.getDefaultHostnameVerifier());
- }
- }
二、com.ning异步请求async-http-client
1、引入文件
- <dependency>
- <groupId>com.ning</groupId>
- <artifactId>async-http-client</artifactId>
- <version>1.9.40</version>
- </dependency>
2、http和https的方法封装
涉及常用的post和get的请求,https的ssl双向证书验证。
- import java.security.KeyStore;
- import java.security.SecureRandom;
- import java.util.Map;
- import java.util.Set;
- import java.util.concurrent.Future;
- import javax.net.ssl.KeyManagerFactory;
- import javax.net.ssl.SSLContext;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- import com.ning.http.client.AsyncHttpClient;
- import com.ning.http.client.AsyncHttpClientConfig;
- import com.ning.http.client.Response;
- /**
- * 创建时间:2016年11月8日 下午5:16:32
- *
- * @author andy
- * @version 2.2
- */
- public class HttpKit {
- private static final String DEFAULT_CHARSET = "UTF-8";
- private static final int CONNECT_TIME_OUT = 5000; //链接超时时间3秒
- private static SSLContext wx_ssl_context = null; //微信支付ssl证书
- static{
- Resource resource = new ClassPathResource("wx_apiclient_cert.p12"); //获取微信证书 或者直接从文件流读取
- char[] keyStorePassword = ConfigUtil.getProperty("wx.mchid").toCharArray(); //证书密码
- try {
- KeyStore keystore = KeyStore.getInstance("PKCS12");
- keystore.load(resource.getInputStream(), keyStorePassword);
- KeyManagerFactory keyManagerFactory = KeyManagerFactory
- .getInstance(KeyManagerFactory.getDefaultAlgorithm());
- keyManagerFactory.init(keystore, keyStorePassword);
- SSLContext wx_ssl_context = SSLContext.getInstance("TLS");
- wx_ssl_context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * @description 功能描述: get 请求
- * @param url 请求地址
- * @param params 参数
- * @param headers headers参数
- * @return 请求失败返回null
- */
- public static String get(String url, Map<String, String> params, Map<String, String> headers) {
- AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
- .setConnectTimeout(CONNECT_TIME_OUT).build());
- AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
- builder.setBodyEncoding(DEFAULT_CHARSET);
- if (params != null && !params.isEmpty()) {
- Set<String> keys = params.keySet();
- for (String key : keys) {
- builder.addQueryParam(key, params.get(key));
- }
- }
- if (headers != null && !headers.isEmpty()) {
- Set<String> keys = headers.keySet();
- for (String key : keys) {
- builder.addHeader(key, params.get(key));
- }
- }
- Future<Response> f = builder.execute();
- String body = null;
- try {
- body = f.get().getResponseBody(DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- }
- http.close();
- return body;
- }
- /**
- * @description 功能描述: get 请求
- * @param url 请求地址
- * @return 请求失败返回null
- */
- public static String get(String url) {
- return get(url, null);
- }
- /**
- * @description 功能描述: get 请求
- * @param url 请求地址
- * @param params 参数
- * @return 请求失败返回null
- */
- public static String get(String url, Map<String, String> params) {
- return get(url, params, null);
- }
- /**
- * @description 功能描述: post 请求
- * @param url 请求地址
- * @param params 参数
- * @return 请求失败返回null
- */
- public static String post(String url, Map<String, String> params) {
- AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
- .setConnectTimeout(CONNECT_TIME_OUT).build());
- AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
- builder.setBodyEncoding(DEFAULT_CHARSET);
- if (params != null && !params.isEmpty()) {
- Set<String> keys = params.keySet();
- for (String key : keys) {
- builder.addQueryParam(key, params.get(key));
- }
- }
- Future<Response> f = builder.execute();
- String body = null;
- try {
- body = f.get().getResponseBody(DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- }
- http.close();
- return body;
- }
- /**
- * @description 功能描述: post 请求
- * @param url 请求地址
- * @param s 参数xml
- * @return 请求失败返回null
- */
- public static String post(String url, String s) {
- AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
- .setConnectTimeout(CONNECT_TIME_OUT).build());
- AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
- builder.setBodyEncoding(DEFAULT_CHARSET);
- builder.setBody(s);
- Future<Response> f = builder.execute();
- String body = null;
- try {
- body = f.get().getResponseBody(DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- }
- http.close();
- return body;
- }
- /**
- * @description 功能描述: post https请求,服务器双向证书验证
- * @param url 请求地址
- * @param params 参数
- * @return 请求失败返回null
- */
- public static String posts(String url, Map<String, String> params){
- AsyncHttpClient http = new AsyncHttpClient(
- new AsyncHttpClientConfig.Builder()
- .setConnectTimeout(CONNECT_TIME_OUT)
- .setSSLContext(wx_ssl_context)
- .build());
- AsyncHttpClient.BoundRequestBuilder bbuilder = http.preparePost(url);
- bbuilder.setBodyEncoding(DEFAULT_CHARSET);
- if (params != null && !params.isEmpty()) {
- Set<String> keys = params.keySet();
- for (String key : keys) {
- bbuilder.addQueryParam(key, params.get(key));
- }
- }
- Future<Response> f = bbuilder.execute();
- String body = null;
- try {
- body = f.get().getResponseBody(DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- }
- http.close();
- return body;
- }
- /**
- * @description 功能描述: post https请求,服务器双向证书验证
- * @param url 请求地址
- * @param s 参数xml
- * @return 请求失败返回null
- */
- public static String posts(String url, String s) {
- AsyncHttpClient http = new AsyncHttpClient(
- new AsyncHttpClientConfig.Builder()
- .setConnectTimeout(CONNECT_TIME_OUT)
- .setSSLContext(wx_ssl_context).build());
- AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
- builder.setBodyEncoding(DEFAULT_CHARSET);
- builder.setBody(s);
- Future<Response> f = builder.execute();
- String body = null;
- try {
- body = f.get().getResponseBody(DEFAULT_CHARSET);
- } catch (Exception e) {
- e.printStackTrace();
- }
- http.close();
- return body;
- }
- }
三、测试
相同结果下,对同一网络请求平均测试20次请求性能
对于少量的网络请求来说httpclient和异步的async-http-client相差无几,甚至比异步还要快,但是在大量网络请求来说异步性能可能更高,但是上面需要优化如减少链接创建、设置超时时间、设置重试次数等等。
Http和Https网络同步请求httpclient和异步请求async-http-client的更多相关文章
- java判断请求是否ajax异步请求
java判断请求是否ajax异步请求 解决方法: if (request.getHeader("x-requested-with") != null && re ...
- 普通B/S架构模式同步请求与AJAX异步请求区别(个人理解)
在上次面试的时候有被问到过AJAX同步与异步之间的概念问题,之前没有涉及到异步与同步的知识,所以特意脑补了一下,不是很全面... 同步请求流程:提交请求(POST/GET表单相似的提交操作)---服务 ...
- .Net core webapi使用httpClient发送异步请求遇到TaskCanceledException: A task was canceled
前言:本人最近较多使用.net core的项目,最近在使用httpClient发送请求的时候,遇到服务器处理时间较长时,就老是会报异常:TaskCanceledException: A task wa ...
- .Net WebRequest异步请求与WebClient异步请求
很多情况下一般会使用同步方式发出请求,直到响应后再做后续的逻辑处理等,但有时候后续的逻辑处理不依赖于请求的结果或者是可以挂起等到响应后再处理,又或者是为了解决UI“假死”的现象,这时可以使用异步请求 ...
- 原生js--编码请求主体(异步请求)
1.表单编码请求 需要对每个表单元素进行普通的URL编码,使用“=”把编码后的名字和值分开,并使用“&”分开名值对. 例如:a=b&c=d 表单数据编码的MIME类型:applicat ...
- Android okHttp网络请求之Get/Post请求
前言: 之前项目中一直使用的Xutils开源框架,从xutils 2.1.5版本使用到最近的xutils 3.0,使用起来也是蛮方便的,只不过最近想着完善一下app中使用的开源框架,由于Xutils里 ...
- NSURLConnection同步与异步请求 问题
NSURLConnection目前有两个异步请求方法,异步请求中其中一个是代理.一个同步方法.有前辈已经详细介绍,见:http://blog.csdn.net/xyz_lmn/article/deta ...
- 异步请求之ajax
一.初识ajax 1.下载引入jQuery <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"& ...
- PHP异步请求之fsockopen()方法详解
正常情况下,PHP执行的都是同步请求,代码自上而下依次执行,但有些场景如发送邮件.执行耗时任务等操作时就不适用于同步请求,只能使用异步处理请求. 场景要求: 客户端调用服务器a.php接口,需要执行一 ...
随机推荐
- 如何在苹果官网下载旧版本的Xcode
如何在苹果官网下载旧版本的Xcode 前段时间XcodeGhost事件让很多应用中招,不乏一些知名的互联网公司开发的应用.事件的起因是开发者使用了非官方的Xcode,这些Xcode带有xcodegho ...
- [ python ] 类的组合
首先,使用面向对象是一个人狗大战的实例: class Person: def __init__(self, name, hp, aggr, sex): self.name = name self.hp ...
- tab切换 jQuery
$('p.guidan-load1').click(function(){ $("p.guidan-load1").removeClass("guidan-load12& ...
- linux命令(11):df命令
1.查看磁盘空间和当前的磁盘数:df –lh或者df –i 2.显示指定类型磁盘:df -t ext4 3.列出各文件系统的i节点使用情况:df -ia 4.列出文件系统的类型:df -T
- 【转载】Web开发技术发展历史-版本2
原文在这里. Web开发的发展史 导读:Arunr 把过去 15 年以来,Web开发从最初的纯 HTML 到 CGI.PHP\JSP\ASP.Ajax.Rails.NodeJS 这个过程简要地进行了介 ...
- HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment
解决方案:修改catalina.sh 文件加上-Djava.awt.headless=true JAVA_OPTS="$JAVA_OPTS $JSSE_OPTS -Djava.awt.hea ...
- JSTL 1.1与JSTL 1.2之间的区别?如何下载JSTL 1.2?
JSTL 1.1与JSTL 1.2之间的区别?如何下载JSTL 1.2? JSTL 1.2中不要求standard.jar架包 您可以在Maven中央仓库中找到它们: http://repo2.mav ...
- es6字符串模板总结
我们平时用原生js插入标签或者用node.js写数据库语言时候,经常需要大量的字符串进行转义,很容易出错,有了es6的字符串模板,就再也不用担心会出错了 1.模板中的变量写在${}中,${}中的值可以 ...
- JDBC浅析
今天简单的说一下jdbc,本来这玩意儿也很简单. 大家只需要记住其中的几个重要的类就行了,它们都在sql包里.今天主要是拿mysql来连接.先看一下主要的几个类吧. 1.Conenction 2.St ...
- 从零开始做SSH项目(二)
使用hibernate测试加载数据.删除数据和修改数据等功能时,针对的是与数据库表user对应的User. 为了简化对其他数据表对应的实体类的持久化操作,可以在项目中创建一个BaseHibernate ...