restTemplate方式
工具类HttpsClientUtils
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
/**
* @params
* @return
* @method Https 调用忽略 SSL
* @description
* @author XXXX
* @date 2021/11/16 16:26
*/
public class HttpsClientUtils {
public static RestTemplate getInstance(Proxy proxy, int connTimeout, int readTimeout, boolean enableSslCheck) {
final RestTemplate restTemplate = new RestTemplate();
// sslIgnore
SimpleClientHttpRequestFactory requestFactory;
if (!enableSslCheck) {
requestFactory = getUnsafeClientHttpRequestFactory();
} else {
requestFactory = new SimpleClientHttpRequestFactory();
}
// proxy
if (proxy != null) {
requestFactory.setProxy(proxy);
}
// timeout
requestFactory.setConnectTimeout(connTimeout);
requestFactory.setReadTimeout(readTimeout);
restTemplate.setRequestFactory(requestFactory);
return restTemplate;
}
private static SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory() {
TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
final SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, byPassTrustManagers, new SecureRandom());
sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
return new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection,
@NotNull String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setSSLSocketFactory(
sslContext.getSocketFactory());
}
}
};
}
public static RestTemplate getInstance(Proxy proxy, boolean enableSsLCheck) {
return getInstance(proxy, -1, -1, enableSsLCheck);
}
}
在代理中使用
@Slf4j
@Component("proxy.jflhtoken")
public class TokenHandler extends ProxyHandler {
@Override
protected MultiValueMap<String, Object> encodeParam(String serialno, JSONObject config, MultiValueMap<String, Object> param) throws FailException, ProxyException {
return param;
}
@Override
protected String excute(YwztProxy proxy, JSONObject config, MultiValueMap<String, Object> param) throws ProxyException, FailException {
//Https调用忽略 SSL
RestTemplate restTemplateToken = HttpsClientUtils.getInstance(null,false);
HttpHeaders headersToken = new HttpHeaders();
headersToken.add("Content-Type", MediaType.APPLICATION_JSON.toString());
headersToken.add("X-Requested-With", "XMLHttpRequest");
JSONObject jsonObject = new JSONObject();
if (!StringUtils.isEmpty(config.get("username")))
jsonObject.put("username", config.get("username").toString());
if (!StringUtils.isEmpty(config.get("password")))
jsonObject.put("password", config.get("password").toString());
HttpEntity requestEntityToken = new HttpEntity(jsonObject.toJSONString(), headersToken);
ResponseEntity<String> responseEntityToken = restTemplateToken.postForEntity(proxy.getUrl(), requestEntityToken, String.class);
return responseEntityToken.getBody();
}
@Override
protected String decodeResult(String serialno, JSONObject config, String resultString) {
return resultString;
}
}
httpClient方式
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
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.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class TestHTTPS {
private static Logger logger = LoggerFactory.getLogger(TestHTTPS.class);
public static void main(String[] args) {
HttpHeaders headersToken = new HttpHeaders();
headersToken.add("Content-Type", MediaType.APPLICATION_JSON.toString());
headersToken.add("X-Requested-With", "XMLHttpRequest");
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "ASDXDDDSSDDDDSS");
jsonObject.put("password", "BDDDDDDDDDDDDDD");
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
String url = "https://qew.ee.ty.hy.cn/tip/api/login";
httpClient = createIgnoreSSLHttpClient();
if (httpClient == null) {
logger.error("HttpClient create fail.");
return;
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("utf-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("NO_OK : " + null);
} else {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("OK : " + result);
}
} 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();
}
}
}
}
public static CloseableHttpClient createIgnoreSSLHttpClient() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}