1、创建RestTemplate 对象
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}
2、普通接口调用
//GET 方式调用
Map<String, String> vars = Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject(
"https://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);
//post方式调用
String url = "http://127.0.0.1:8080/hello";
JSONObject param = new JSONObject();
ResponseEntity<JSONObject> responseEntity=restTemplate.postForEntity(url,params,JSONObject.class);
int statusCodeValue = responseEntity.getStatusCodeValue();
HttpHeaders headers = responseEntity.getHeaders();
JSONObject body = responseEntity.getBody();
3、添加 Header 和 Cookie
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl("127.0.0.1:8080").
path("/test").build(true);
URI uri = uriComponents.toUri();
RequestEntity<JSONObject> requestEntity = RequestEntity.post(uri).
// 添加 cookie(这边有个问题,假如我们要设置 cookie 的生命周期,作用域等参数我们要怎么操作)
header(HttpHeaders.COOKIE,"key1=value1").
// 添加 header
header(("MyRequestHeader", "MyValue")
accept(MediaType.APPLICATION_JSON).
contentType(MediaType.APPLICATION_JSON).
body(requestParam);
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(requestEntity,JSONObject.class);
// 响应结果
JSONObject responseEntityBody = responseEntity.getBody();
常见方法:
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为OkHttp、HttpClient、HttpURLConnection、OKHttp和Volley。
案例:
import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public void afterPropertiesSet() throws UnsupportedEncodingException {
Collection<Header> defaultHeaders = new ArrayList<Header>();
Header header = new BasicHeader("Authorization",
"Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8")));
defaultHeaders.add(header);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("apollo", ""));
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
.setDefaultHeaders(defaultHeaders).build();
restTemplate = new RestTemplate(httpMessageConverters.getConverters());
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(portalConfig.connectTimeout());
requestFactory.setReadTimeout(portalConfig.readTimeout());
restTemplate.setRequestFactory(requestFactory);
}