本系列文章为大家提供常用小工具的Demo
侧重点并非代码如何实现,因为大家都能写
目的是为大家节省开发时间,力求“拿来直接就能用”
用最快的时间完成开发任务
在应用内部需要调用外部的api时使用
同时兼容https类型请求
(正常在调用https类型请求时会报以下异常,该工具解决了该问题)
还是老话:方法有很多,效率至上即可。
源码分为三部分:
大家只需关注第三部分,了解使用方式,前两部分直接复制粘贴即可。
以下为各部分源码,具体说明已写在注释中,应该无需我多言了:
Part 1
/**
* 兼容调Https接口
* @Author mazq
* @Date 2020/06/04 17:16
* @Param
* @return
*/
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {// http协议
//throw new RuntimeException("An instance of HttpsURLConnection is expected");
super.prepareConnection(connection, httpMethod);
}
if (connection instanceof HttpsURLConnection) {// https协议,修改协议版本
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// 信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext ctx = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
super.prepareConnection(httpsConnection, httpMethod);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Part 2
/**
*
* RestTemplate 远程调用工具类
*
*
*
* @author mazq
*
*/
@Component
public class RestTemplateUtils {
public static RestTemplate geTemplate(){
return new RestTemplate(new HttpsClientRequestFactory());
}
/**
* GET请求调用方式
* @Author mazq
* @Date 2020/06/01 13:47
* @Param [url, responseType, uriVariables]
* @return org.springframework.http.ResponseEntity
*/
public static ResponseEntity getForEntity(String url, Class responseType, Map uriVariables) {
return geTemplate().getForEntity(url, responseType, uriVariables);
}
/**
* POST请求调用方式
* @Author mazq
* @Date 2020/06/01 13:47
* @Param [url, headers, body, responseType]
* @return org.springframework.http.ResponseEntity
*/
public static ResponseEntity postForEntity(String url,HttpHeaders headers, Object requestBody , Class responseType ){
HttpEntity
Part 3
MultiValueMap map= new LinkedMultiValueMap();
map.add("username","");
map.add("password","");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
log.info("远程调用传递参数:");
log.info("headers:" + headers);
log.info("body:" + map);
ResponseEntity responseEntity = RestTemplateUtils.postForEntity("https://....",headers,map,String.class);
log.info("远程调用返回结果:" + responseEntity);
更多内容在公众号:浩说编程。
页面更新:2024-04-13
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号