apache httpclient HTTPS发送JSON调用接口实例
2018-03-28 23:59
337 查看
1.目的:调用第三方接口
2.协议:https
3.报文格式:JSON
4.依赖jar如下 <!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- jsckson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>5.相关代码
1). action类package com.koon.demo1;
import com.fasterxml.jackson.core.JsonProcessingException;
public class XinYongCardAction {
public static void main(String[] args) throws JsonProcessingException {
//uri
String uri = "https://x.xxx.com/xxx/getToken";
String mess = new AssemblingMessTool().getMess();
String returnMess = new HttpsSendMessTool().postReturnMess(uri, mess);
System.out.println(returnMess);
}
}
2). 发送报文工具类package com.koon.demo1;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
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.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.util.EntityUtils;
public class HttpsSendMessTool {
public String getReturnMess(String uri) {
String returnMess = "";
CloseableHttpClient httpClient = null;
HttpGet httpGet = null;
try {
httpClient = (CloseableHttpClient) wrapClient();
httpGet = new HttpGet(uri);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
returnMess = EntityUtils.toString(httpEntity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return returnMess;
}
public String postReturnMess(String uri, String jsonMess) {
String returnMess = "";
CloseableHttpClient httpClient = null;
HttpPost httpPost;
try {
httpClient = (CloseableHttpClient) wrapClient();
httpPost = new HttpPost(uri);
StringEntity entity = new StringEntity(jsonMess);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
returnMess = EntityUtils.toString(resEntity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return returnMess;
}
public static HttpClient wrapClient() {
try {
SSLContext context = SSLContext.getInstance("SSL");
X509TrustManager manager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
};
context.init(null, new TrustManager[] { manager }, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(context).build();
return httpClient;
} catch (Exception e) {
System.out.println(123);
return HttpClients.createDefault();
}
}
}
3). JSON工具类package com.koon.demo1;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTool {
public String getJson(Map<String, Object> mess) {
String result = "";
ObjectMapper mapper = new ObjectMapper();
try {
result = mapper.writeValueAsString(mess);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
4). 拼装消息对象类
2.协议:https
3.报文格式:JSON
4.依赖jar如下 <!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- jsckson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>5.相关代码
1). action类package com.koon.demo1;
import com.fasterxml.jackson.core.JsonProcessingException;
public class XinYongCardAction {
public static void main(String[] args) throws JsonProcessingException {
//uri
String uri = "https://x.xxx.com/xxx/getToken";
String mess = new AssemblingMessTool().getMess();
String returnMess = new HttpsSendMessTool().postReturnMess(uri, mess);
System.out.println(returnMess);
}
}
2). 发送报文工具类package com.koon.demo1;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
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.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.util.EntityUtils;
public class HttpsSendMessTool {
public String getReturnMess(String uri) {
String returnMess = "";
CloseableHttpClient httpClient = null;
HttpGet httpGet = null;
try {
httpClient = (CloseableHttpClient) wrapClient();
httpGet = new HttpGet(uri);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
returnMess = EntityUtils.toString(httpEntity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return returnMess;
}
public String postReturnMess(String uri, String jsonMess) {
String returnMess = "";
CloseableHttpClient httpClient = null;
HttpPost httpPost;
try {
httpClient = (CloseableHttpClient) wrapClient();
httpPost = new HttpPost(uri);
StringEntity entity = new StringEntity(jsonMess);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
returnMess = EntityUtils.toString(resEntity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return returnMess;
}
public static HttpClient wrapClient() {
try {
SSLContext context = SSLContext.getInstance("SSL");
X509TrustManager manager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
};
context.init(null, new TrustManager[] { manager }, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(context).build();
return httpClient;
} catch (Exception e) {
System.out.println(123);
return HttpClients.createDefault();
}
}
}
3). JSON工具类package com.koon.demo1;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTool {
public String getJson(Map<String, Object> mess) {
String result = "";
ObjectMapper mapper = new ObjectMapper();
try {
result = mapper.writeValueAsString(mess);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
4). 拼装消息对象类
package com.koon.demo1; import java.security.MessageDigest; import java.util.HashMap; import java.util.Map; public class AssemblingMessTool { private String timestamp; private String appKey; private String sign; public AssemblingMessTool() { this.timestamp = System.currentTimeMillis() + ""; this.appKey = "key"; String tmp = "appKey=" + this.appKey + "×tamp" + this.timestamp + "&appSecret=192006250b4c09247ec02edce69f6a2d"; this.sign = MD5(tmp).toUpperCase(); } public String getMess() { Map<String, Object> parent = new HashMap<>(); Map<String, Object> son = new HashMap<>(); son.put("appKey", this.appKey); son.put("timestamp", this.timestamp); parent.put("sign", this.sign); parent.put("params", son); return new JsonTool().getJson(parent); } private String MD5(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(s.getBytes("utf-8")); return toHex(bytes); } catch (Exception e) { throw new RuntimeException(e); } } private static String toHex(byte[] bytes) { final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); StringBuilder ret = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]); ret.append(HEX_DIGITS[bytes[i] & 0x0f]); } return ret.toString(); } public String getTimeStamp() { return timestamp; } public void setTimeStamp(String timeStamp) { this.timestamp = timeStamp; } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
相关文章推荐
- httpClient发送get请求调用接口
- HttpClient详细实例,Httoclient调用https实例,避免https SSL认证
- 使用Apache提供的HttpClient发送https请求
- SAP中用json数据格式调用http接口发送短信邮件案例
- Java HttpClient在外围接口调用实例
- Android HTTP实例 使用GET方法和POST方法发送请求(通过Apache接口实现)
- http请求远程接口获得Json数据(2) --- 利用HttpClient发送post/get请求
- SAP中用json数据格式调用http接口发送短信邮件案例
- 使用apache的httpclient发送post请求传送和解析json
- 使用搜狐Sendcloud的Webapi发送邮件:Jodd和Apache Httpclient
- HttpClient 之 发送Https请求
- 通过4.4httpclient访问http和调用https
- android使用apache httpclient发送post请求
- JAVA发送http请求,调用http接口与方法
- ABAP接口之Http发送json报文
- httpClient post发送json数据
- 【实战】(二)android模拟qq登录(apache的httpClient发送get和post请求)
- HttpClient 发送 HTTP、HTTPS 请求的简单封装
- 给MySQL增加mysql-udf-http和mysql-udf-json自定义函数,让MySQL有调用http接口和查询直接回JSON的能力
- HttpClient学习笔记 --发送Http和Https请求