1.restTemplate的配置
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);// 单位为ms
factory.setConnectTimeout(5000);// 单位为ms
return factory;
}
2.不同header传参
2.1 application/x-www-form-urlencoded
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded;charset=UTF-8");
headers.setContentType(type);
// Header中设置cookie
// List<String> cookies = new ArrayList<>();
// cookies.add("JSESSIONID=" + creditphone);
// headers.put(HttpHeaders.COOKIE, cookies);
MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
postParams.add("phone", "123");
HttpEntity<MultiValueMap<String, String>> paramsEntity = new HttpEntity<>(postParams, headers);
response = restTemplate.postForEntity("url", paramsEntity, String.class);
2.2 application/json
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
headers.setContentType(type);
HttpEntity<String> paramsEntity = new HttpEntity<>(json, headers);
response = restTemplate.postForEntity("url", paramsEntity, String.class);