1.准备代理类
package cn.com.cpic.pms.facade.verify;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
/**
* @author hjh
* @description: 给restTemplate加代理
* @date 2021/12/2 10:03
*/
@Slf4j
public class HttpRequestFactory {
public static HttpComponentsClientHttpRequestFactory generateHttpsRequestFactory(String pubProxyIp,Integer pubProxyPort) {
try {
TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory connectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
// 代理url, port
httpClientBuilder.setProxy(new HttpHost(pubProxyIp, pubProxyPort, "http"));
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
factory.setConnectTimeout(10 * 1000);
factory.setReadTimeout(30 * 1000);
return factory;
} catch (Exception e) {
log.error("创建HttpsRestTemplate失败", e);
throw new RuntimeException("创建HttpsRestTemplate失败", e);
}
}
}
2.将请求参数JSON化后发送请求
这次提供的仅仅是思路步骤,具体逻辑内容可根据自己需求改变
public String TestRest(TestReq req) throws ArkRuntimeException {
RestTemplate restTemplate=new RestTemplate();
restTemplate.setRequestFactory(HttpRequestFactory.generateHttpsRequestFactory("代理ip",代理端口);
String reqJson = JSONObject.toJSONString(req);
log.info("reqJson----->"+reqJson);
//设置头部及报文体
HttpEntity<String> formEntity = pubUtil.getHeadersInfo(reqJson,eperAppid);
log.info("formEntity----->"+formEntity.toString());
String url="http://ip:port/test";
log.info("url----->"+url);
ResponseEntity<String> result = null;
try{
result = restTemplate.postForEntity(url,formEntity, String.class);
log.info("测试返回报文----->"+result);
} catch (Exception e) {
log.error("调用接口异常"+e.getMessage());
throw new Exception("调用接口异常");
}
TestBody responseBody = JSONObject.parseObject(result.getBody(),TestBody.class);
TestResp resp = JSONObject.parseObject(responseBody.具体要的内容(),TestResp.class);
String str = "";
if ("0000".equals(resp.getCode())) {
str = resp.getData();
} else {
throw new Exception(resp.getMsg());
}
return str;
}