Hello,大家好呀,我是你们的Jessica老哥,不知不觉,到了3月份了,又是一年一度的金三银四,老哥和大家一样,想换工作,于是呢,更新资料,投简历。试想着把自己的劳动价值卖的更高一点。   没想到,今年好像行情有点不太对劲呀,往年跟HR打个招呼,人家还会要你简历,可现在呢,人家是已读不回,硬气了。也许是老哥的学历低,再加上大环境不好和学编程的人越来越多,不好找工作咯。算了,算了,老哥继续苟着吧。

这次给大家带来的是 RestTemplate 请求https接口,我们都知道,https接口一般是需要证书才能访问的,但是我们可以采取一些特殊的手段,跳过证书验证。下面,老哥讲下具体的代码

1、首先,配置一个 RestTemplate的bean,说明:RestTemplate是spring-web自带的,我们不需要额外引入什么包

@Configuration

public class RestTemplateConfig {

/**

* 构建支持忽略自签名证书的Restemplate的bean

* @return 支持发起https请求的RestTemplate对象

* @throws KeyStoreException 证书异常

* @throws NoSuchAlgorithmException 加密算法不可用异常

* @throws KeyManagementException 密钥管理异常

*/

@Bean("httpsTemplate")

public RestTemplate createHttpsRestTemplate()

throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;

SSLContext sslContext = SSLContexts.custom()

.loadTrustMaterial(null, acceptingTrustStrategy)

.build();

SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(

sslContext, new NoopHostnameVerifier());

CloseableHttpClient httpClient = HttpClients.custom()

.setSSLSocketFactory(sslFactory)

.build();

HttpComponentsClientHttpRequestFactory factory =

new HttpComponentsClientHttpRequestFactory();

factory.setConnectTimeout(3600000);

factory.setReadTimeout(3600000);

factory.setHttpClient(httpClient);

return new RestTemplate(factory);

}

}

2、然后,配置一下 RestTemplate 工具类

@Slf4j

@Component

public class RestTemplateUtil {

private static RestTemplate restTemplate;

@Autowired

private RestTemplate httpsTemplate;

@PostConstruct

public void afterPropertiesSet() {

RestTemplateUtil.restTemplate = httpsTemplate;

}

/**

* Get 请求 不带参数 没有请求头 没有请求参数 没有请求体

* @param url

* @return

*/

public static String sendSimple(String url) {

return sendSimple(url, null, HttpMethod.GET, null,new HttpHeaders());

}

/**

* Get 请求 url带请求参数

* @param url

* @param urlParam

* @return

*/

public static String sendSimple(String url, Map urlParam) {

return sendSimple(url, urlParam, HttpMethod.GET);

}

/**

* Get 请求 url带请求参数 请求头携带参数

* @param url

* @param urlParam

* @param headers

* @return

*/

public static String sendSimple(String url, Map urlParam, HttpHeaders headers) {

return sendSimple(url, urlParam, HttpMethod.GET,null, headers);

}

public static String sendSimple(String url, Map urlParam, HttpMethod method) {

return sendSimple(url, urlParam, method, null,new HttpHeaders());

}

/**

* Get发送简单请求,不含body

*

* @param url url

* @param urlParam 用?和&拼接在url后面的参数

* @param method 请求方式

* @param headers 请求头

* @return body

*/

public static String sendSimple(String url, Map urlParam, HttpMethod method, Map header,HttpHeaders headers) {

if (urlParam == null) {

urlParam = new HashMap<>(0);

}

// url参数拼接

url = handleUrlParam(url, urlParam);

//填充属性到请求头

fillParamsToHttpHeader(header,headers);

HttpEntity> requestEntity = new HttpEntity<>(null, headers);

log.info("请求地址为: "+url);

return restTemplate.exchange(url, method, requestEntity, String.class, urlParam).getBody();

}

/**

* 表单提交,没有请求头和url拼接,有请求体

* @param url

* @param body

* @return

*/

public static String sendForm(String url, Map body) {

return sendForm(url, null, body, HttpMethod.POST, new HttpHeaders());

}

/**

* 表单提交,有url拼接和请求体

* @param url

* @param body

* @return

*/

public static String sendForm(String url, Map urlParam, Map body) {

return sendForm(url, urlParam, body, HttpMethod.POST, new HttpHeaders());

}

/**

* 表单提交,有url拼接和请求头、请求体

* @param url

* @param urlParam

* @param header

* @param body

* @return

*/

public static String sendForm(String url, Map urlParam,Map header, Map body) {

return sendForm(url, urlParam, body, HttpMethod.POST, new HttpHeaders());

}

/**

* 表单提交,有请求头和请求体 指定请求方式

* @param url

* @param urlParam

* @param body

* @param method

* @return

*/

public static String sendForm(String url, Map urlParam, Map body, HttpMethod method) {

return sendForm(url, urlParam, body, method, new HttpHeaders());

}

public static String sendForm(String url,Map header, Map body,

HttpMethod method, HttpHeaders headers) {

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

return send(url, header, body, method, headers,null);

}

public static String sendForm(String url, Map header,Map body,

HttpMethod method, HttpHeaders headers, Map urlParam) {

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

return send(url, header,body, method, headers,urlParam);

}

public static String sendJson(String url, Map body) {

return sendJson(url, null, body, HttpMethod.POST, new HttpHeaders());

}

public static String sendJson(String url, Map urlParam, Map body) {

return sendJson(url, urlParam, body, HttpMethod.POST, new HttpHeaders());

}

public static String sendJson(String url, Map head, Map body, HttpMethod method,Map urlParam) {

return sendJson(url, head, body, method, new HttpHeaders(),urlParam);

}

public static String sendJson(String url, Map head, Map body,

HttpMethod method, HttpHeaders headers,Map urlParam) {

headers.setContentType(MediaType.APPLICATION_JSON);

return send(url, head, body, method, headers,urlParam);

}

/**

* 复杂请求发送

*

* @param url url

* @param head 请求头

* @param body 请求体

* @param method 请求方式

* @param headers 实际请求头

* @param urlParam 用?和&拼接在url后面的参数

*

*/

public static String send(String url, Map head,Map body, HttpMethod method,

HttpHeaders headers, Map urlParam) {

try {

if (urlParam == null) {

urlParam = new HashMap<>(16);

}

// Get 请求 url参数拼接

if (method.equals(HttpMethod.GET)){

url = handleUrlParam(url, urlParam);

}

//填充参数到Http请求头

fillParamsToHttpHeader(head,headers);

log.info("请求地址为: "+url);

if (Objects.equals(headers.getContentType(), MediaType.APPLICATION_JSON)) {

String str=null;

if (Objects.isNull(body)){

str=new JSONObject().toJSONString();

}else {

JSONObject jsonObject = new JSONObject();

jsonObject.putAll(body);

str=jsonObject.toJSONString();

}

HttpEntity requestEntity = new HttpEntity<>(str,headers);

return restTemplate.postForEntity(url,requestEntity,String.class).getBody();

}

if (Objects.equals(headers.getContentType(), MediaType.APPLICATION_FORM_URLENCODED)) {

// body参数处理

MultiValueMap param =new LinkedMultiValueMap<>();

for (Map.Entry next : body.entrySet()) {

param.add(next.getKey(), (String) next.getValue());

}

HttpEntity > requestEntity = new HttpEntity<>(param, headers);

return restTemplate.exchange(url, method, requestEntity, String.class, urlParam).getBody();

}

}catch (Exception e){

log.error(e.getMessage());

e.printStackTrace();

}

return null;

}

/**

* url参数拼接

*

* @param url

* @param urlParam

* @return

*/

private static String handleUrlParam(String url, Map urlParam) {

if (urlParam == null || urlParam.isEmpty()) {

return url;

}

Iterator> iterator = urlParam.entrySet().iterator();

StringBuilder urlBuilder = new StringBuilder(url);

urlBuilder.append("?");

while (iterator.hasNext()) {

Map.Entry entry = iterator.next();

urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");

}

urlBuilder.deleteCharAt(urlBuilder.length() - 1);

return String.valueOf(urlBuilder);

}

/**

* 填充参数到请求头

*

* @param heads

* @param headers

*/

public static void fillParamsToHttpHeader(Map heads, HttpHeaders headers) {

if (!Objects.isNull(heads)) {

Set keySet = heads.keySet();

for (String s : keySet) {

headers.add(s,String.valueOf(heads.get(s)));

}

}

}

}

3、使用,只需要按照下面的模板,传递参数即可

public static void main(String[] args) {

//分别填入请求头和请求体参数即可

Map headerMap = new ConcurrentHashMap<>(16);

Map bodyMap = new ConcurrentHashMap<>(16);

String url = String.format("https://%s/test", "你的主机地址");

String jsonStr = RestTemplateUtil.sendForm(url, headerMap, bodyMap);

User user = JSONObject.parseObject(jsonStr, User.class);

System.out.println(user);

}

3A、最后,各位小伙伴,麻烦给老哥一个点赞、关注、收藏三连好吗,你的支持是老哥更新最大的动力,谢谢!

原文链接:

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。