一、首先需要编写一个RestTemplate配置类,放在入口类所在包或者其子包下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* Created by qiaos on 2018/06/28.
* RestTemplate配置类
*/
@Configuration
public class RestTemplateConfig {
@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;
}
}
|
二、注入接口
//调用接口 @Autowired private RestTemplate restTemplate;
三、方法中具体实现:
import org.springframework.http.*;
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
//添加请求的参数
params.add("hello", "hello"); //必传
params.add("world", "world"); //选传
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
// 执行HTTP请求
ResponseEntity<String> response = restTemplate.exchange("此处为url地址", HttpMethod.POST, requestEntity, String.class); //最后的参数需要用String.class 使用其他的会报错
String body = response.getBody();
if(body != null){
JSONObject data = (JSONObject) JSON.parse(body);
//data就是返回的结果
}else{
}
-------------------------------------------------------------------------------------------------------------
请求头的那块设置:
APPLICATION_FORM_URLENCODED ==》 application/x-www-form-urlencoded
类型有很多 根据需要修改就ojbk了。