RestTemplate发送HTTPS请求。
程序员文章站
2022-06-24 22:30:50
...
如果您的jdk是1.6或者1.7版本,请先看我的另一篇博客:https://blog.csdn.net/weixin_40723540/article/details/104652593
工具类
package com.pj.acl.interceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.security.cert.X509Certificate;
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
super.prepareConnection(httpsConnection, httpMethod);
httpsConnection.setFollowRedirects(false);
httpsConnection.setInstanceFollowRedirects(false);
httpsConnection.setReadTimeout(5000);
httpsConnection.setConnectTimeout(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
// 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
// 这些默认的服务的最低质量要求保密保护和服务器身份验证
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
// 返回的密码套件可用于SSL连接启用的名字
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port,
final boolean autoClose) throws IOException {
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
private Socket overrideProtocol(final Socket socket) {
if (!(socket instanceof SSLSocket)) {
throw new RuntimeException("An instance of SSLSocket is expected");
}
//enabledProtocols里面包含了当前jdk支持的SSL/TLS协议版本
String[] enabledProtocols = ((SSLSocket) socket).getEnabledProtocols();
//((SSLSocket) socket).setEnabledProtocols(new String[]{"SSLv3"});
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
try {
socket.setSoTimeout(500);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return socket;
}
}
}
调用实例:
package com.pj.acl.interceptor;
import java.net.URI;
public class RestTemplateTest {
public static ResponseEntity<?> exchange(HttpMethod method, String url, String params, HttpHeaders headers, Class<?> responseType) {
ResponseEntity<?> result = null;
HttpEntity<String> httpEntity;
RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
headers = headers == null ? new HttpHeaders() : headers;
headers.remove("Content-Length");
httpEntity = new HttpEntity<String>(params, headers);
try {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = new URI(builder.build().encode().toString());
result = restTemplate.exchange(uri, method, httpEntity, responseType);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String args[]){
try {
String requestDMS = RestTemplateTest.requestDMS("https://192.168.2.223/wms", null, HttpMethod.GET, 0);
//String requestDMS = RestTemplateTest.requestDMS("https://www.baidu.com/", null, HttpMethod.GET, 0);
System.out.println(requestDMS);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String requestDMS(String url,String params,HttpMethod method,int t) throws Exception{
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8;text/html;");
headers.setConnection("keep-alive");
headers.add("Referrer", "no-referrer-when-downgrade");
headers.add("host", "dms.tdyh.cn");
URI uri = new URI("https://dms.tdyh.cn");
headers.setLocation(uri);
headers.add("content-length", "413");
headers.add("server", "Microsoft-IIS/10.0");
return (String) RestTemplateTest.exchange(method, url, params,headers, String.class).getBody();
}
}
上一篇: 小笔记 DLL导出 和 Lib引用
下一篇: httpclient代码
推荐阅读
-
IE6通过get发送奇数个汉字请求会乱码的解决方法_PHP教程
-
php curl 获取https请求的2种方法,curlhttps
-
PHP模拟发送POST请求之三、加强file_get_contents发送POST请求
-
php之curl实现http与https请求的方法,phpcurlhttps请求_PHP教程
-
java发送http get请求的两种方式
-
java发送http get请求的两种方法(总结)
-
IOS开发 支持https请求以及ssl证书配置详解
-
Java 发送http请求上传文件功能实例
-
iOS之Https自签名证书认证及数据请求的封装原理
-
Python 使用requests模块发送GET和POST请求的实现代码