HttpClient

接着上一篇,总结一下HttpClient发送https请求相关的内容。
先简单介绍连接工厂(interface org.apache.http.conn.socket.ConnectionSocketFactory),连接工厂主要用于创建、初始化、连接socket。org.apache.http.conn.socket.PlainConnectionSocketFactory是默认的socket工厂,用于创建无加密(unencrypted)socket对象。创建https需要使用org.apache.http.conn.ssl.SSLConnectionSocketFactoryPlainConnectionSocketFactorySSLConnectionSocketFactory都实现了ConnectionSocketFactory
好了,直接上代码,代码实现的功能是,组装一个发往银联的查询报文(查询交易结果)。

1import java.security.cert.CertificateException; 2import java.security.cert.X509Certificate; 3import java.util.ArrayList; 4import java.util.HashMap; 5import java.util.Iterator; 6import java.util.List; 7import java.util.Map; 8import java.util.Map.Entry; 9 10import javax.net.ssl.SSLContext; 11import javax.net.ssl.TrustManager; 12import javax.net.ssl.X509TrustManager; 13 14import org.apache.http.HttpEntity; 15import org.apache.http.NameValuePair; 16import org.apache.http.client.config.RequestConfig; 17import org.apache.http.client.entity.UrlEncodedFormEntity; 18import org.apache.http.client.methods.CloseableHttpResponse; 19import org.apache.http.client.methods.HttpPost; 20import org.apache.http.conn.ssl.NoopHostnameVerifier; 21import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 22import org.apache.http.impl.client.CloseableHttpClient; 23import org.apache.http.impl.client.HttpClients; 24import org.apache.http.message.BasicNameValuePair; 25import org.apache.http.util.EntityUtils; 26 27/** 28 * This example demonstrates how to create secure connections with a custom SSL 29 * context. 30 */ 31public class ClientCustomSSL { 32 private static String reqStr = "txnType=00&signMethod=01&certId=68759663125&encoding=UTF-8&merId=777290058110048&bizType=000201&txnSubType=00&signature=k0lrWgeLK%2Fx%2B8ajj15QCYfmdQxZSKBjXUJN0bLt17rp87ptogxWgHAAq7EUt8RlEbxD6GaRngwtdLGiy6are45Gj1dBLJBtW2841WIq4Ywzx3oK6538Kfh9ll91GJcZJGYz8LuJoZfii7HFPlpl1ZsPZbbdKP6WFVHNMnGnL9nk9QSa%2BihXGpyK%2Fy1FA42AJpfc%2FTT3BV6C%2FxpoEhXzVckHnniVnCpLdGnPfZOd76wK%2Fa%2BALNmniwUZmMj9uNPwnONIIwL%2FFqrqQinQArolW%2FrcIt9NL7qKvQujM%2BdRvd1fboAHI5bZC3ktVPB0s5QFfsRhSRFghVi4RHOzL8ZG%2FVQ%3D%3D&orderId=20160309145206&version=5.0.0&txnTime=20160309145206&accessType=0"; 33 private static String url = "https://101.231.204.80:5000/gateway/api/queryTrans.do"; 34 35 // 信任管理器 36 private static X509TrustManager tm = new X509TrustManager() { 37 @Override 38 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 39 } 40 41 @Override 42 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 43 } 44 45 @Override 46 public X509Certificate[] getAcceptedIssuers() { 47 return null; 48 } 49 }; 50 51 public final static void main(String[] args) throws Exception { 52 long starttime = System.currentTimeMillis(); 53 SSLContext sslContext = SSLContext.getInstance("TLS"); 54 // 初始化SSL上下文 55 sslContext.init(null, new TrustManager[] { tm }, null); 56 // SSL套接字连接工厂,NoopHostnameVerifier为信任所有服务器 57 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,NoopHostnameVerifier.INSTANCE); 58 /** 59 * 通过setSSLSocketFactory(sslsf)保证httpclient实例能发送Https请求 60 */ 61 CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setMaxConnTotal(50) 62 .setMaxConnPerRoute(50).setDefaultRequestConfig(RequestConfig.custom() 63 .setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build()) 64 .build(); 65 try { 66 67 HttpPost httppost = new HttpPost(url); 68 69 // 设置参数,参数含义不需要理解 70 Map<String, String> map = new HashMap<String, String>(); 71 map.put("txnType","00"); 72 map.put("signMethod","01"); 73 map.put("certId","68759663125"); 74 map.put("encoding","UTF-8"); 75 map.put("merId","777290058110048"); 76 map.put("bizType","000201"); 77 map.put("txnSubType","00"); 78 map.put("signature","k0lrWgeLK%2Fx%2B8ajj15QCYfmdQxZSKBjXUJN0bLt17rp87ptogxWgHAAq7EUt8RlEbxD6GaRngwtdLGiy6are45Gj1dBLJBtW2841WIq4Ywzx3oK6538Kfh9ll91GJcZJGYz8LuJoZfii7HFPlpl1ZsPZbbdKP6WFVHNMnGnL9nk9QSa%2BihXGpyK%2Fy1FA42AJpfc%2FTT3BV6C%2FxpoEhXzVckHnniVnCpLdGnPfZOd76wK%2Fa%2BALNmniwUZmMj9uNPwnONIIwL%2FFqrqQinQArolW%2FrcIt9NL7qKvQujM%2BdRvd1fboAHI5bZC3ktVPB0s5QFfsRhSRFghVi4RHOzL8ZG%2FVQ%3D%3D"); 79 map.put("orderId","20160309145206"); 80 map.put("version","5.0.0"); 81 map.put("txnTime","20160309145206"); 82 map.put("accessType","0"); 83 84 List<NameValuePair> list = new ArrayList<NameValuePair>(); 85 Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); 86 while (iterator.hasNext()) { 87 Entry<String, String> elem = (Entry<String, String>) iterator.next(); 88 list.add(new BasicNameValuePair(elem.getKey(), elem.getValue())); 89 } 90 if (list.size() > 0) { 91 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); 92 httppost.setEntity(entity); 93 } 94 95 System.out.println("executing request " + httppost.getRequestLine()); 96 97 CloseableHttpResponse response = httpclient.execute(httppost); 98 try { 99 HttpEntity entity = response.getEntity(); 100 101 System.out.println("----------------------------------------"); 102 System.out.println(response.getStatusLine()); 103 if (entity != null) { 104 System.out.println("Response content length: " + entity.getContentLength()); 105 } 106 String s = EntityUtils.toString(entity,"UTF-8"); 107 System.out.println("应答内容:" + s); 108 109 EntityUtils.consume(entity); 110 } finally { 111 response.close(); 112 } 113 } finally { 114 httpclient.close(); 115 } 116 117 long endtime = System.currentTimeMillis(); 118 System.out.println("耗时:" + (endtime-starttime) + "ms"); 119 } 120 121}

使用注册器可以保证既能发送http请求也能发送httpsclient请求,代码块如下:

1int httpReqTimeOut = 60000;//60秒 2 3SSLContext sslContext = SSLContext.getInstance("TLS"); 4 // 初始化SSL上下文 5 sslContext.init(null, new TrustManager[] { tm }, null); 6 // SSL套接字连接工厂,NoopHostnameVerifier为信任所有服务器 7 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,NoopHostnameVerifier.INSTANCE); 8 // 注册http套接字工厂和https套接字工厂 9 Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() 10 .register("http", PlainConnectionSocketFactory.INSTANCE) 11 .register("https", sslsf) 12 .build(); 13 // 连接池管理器 14 PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(r); 15 pcm.setMaxTotal(maxConnTotal);//连接池最大连接数 16 pcm.setDefaultMaxPerRoute(maxConnPerRoute);//每个路由最大连接数 17 /** 18 * 请求参数配置 19 * connectionRequestTimeout: 20 * 从连接池中获取连接的超时时间,超过该时间未拿到可用连接, 21 * 会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool 22 * connectTimeout: 23 * 连接上服务器(握手成功)的时间,超出该时间抛出connect timeout 24 * socketTimeout: 25 * 服务器返回数据(response)的时间,超过该时间抛出read timeout 26 */ 27 RequestConfig requestConfig = RequestConfig.custom() 28 .setConnectionRequestTimeout(httpReqTimeOut) 29 .setConnectTimeout(httpReqTimeOut) 30 .setSocketTimeout(httpReqTimeOut) 31 .build(); 32 /** 33 * 构造closeableHttpClient对象 34 */ 35 closeableHttpClient = HttpClients.custom() 36 .setDefaultRequestConfig(requestConfig) 37 .setConnectionManager(pcm) 38 .setRetryHandler(retryHandler) 39 .build();

关键代码为:

1// 注册http套接字工厂和https套接字工厂 2 Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() 3 .register("http", PlainConnectionSocketFactory.INSTANCE) 4 .register("https", sslsf) 5 .build();
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )