目录
一 基本配置
1 简单使用
2 处理中文乱码
3 发送https请求
二 GET
1 getForObject
(1) 不带参数
(2) 带参数-按顺序绑定( http://.../getData/{name}/{age})
(3) 带参数 (http://.../getData?name=xxx&age=xxx)
2 getForEntity
3 为URL设置编码
4 设置请求头
三 POST
1 postForObject
(1) application/x-www-form-urlencoded (无参)
(2) application/x-www-form-urlencoded (有参)
(3) JSON
2 postForEntity
3 带请求头
(1) application/x-www-form-urlencoded
(2) JSON
四 获取状态码非200的Body
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
@Bean
public RestTemplate getRestTemplate(){
RestTemplate restTemplate = new RestTemplate();
//解决中文乱码
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
如果 org.apache.http 包没有引入下面这个依赖
org.apache.httpcomponents
httpclient
4.5.5
服务端:
@GetMapping("/getData")
public Object getData() {
return "收到数据";
}
客户端:
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData";
return restTemplate.getForObject(url, String.class);
}
服务端:
@GetMapping("/getData/{name}/{age}")
public Object getData(@PathVariable("name") String name,
@PathVariable("age") String age) {
return "收到数据:name:"+name+", age:"+age;
}
客户端:
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData/{name}/{age}";
return restTemplate.getForObject(url, String.class, "小东", "18");
}
或
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData/{name}/{age}";
Map map = new HashMap<>();
map.put("name", "小南");
map.put("age", "18");
return restTemplate.getForObject(url, String.class, map);
}
服务端:
@GetMapping("/getData")
public Object getData(Student student) {
return "收到数据:name:"+student.getName()+", age:"+student.getAge();
}
@Data
public class Student {
private String name;
private String age;
}
或
@GetMapping("/getData")
public Object getData(String name, String age) {
return "收到数据:name:"+name+", age:"+age;
}
客户端:
方式1: 使用UriComponentsBuilder
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
builder.queryParam("name", "小南");
builder.queryParam("age", "18");
// 使用 builder.build().toUriString() 防止中文乱码。
//如果直接builder.toUriString()会中文乱码
return restTemplate.getForObject(builder.build().toUriString(), String.class);
}
或
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData";
MultiValueMap params = new LinkedMultiValueMap<>();
params.add("name", "小小");
params.add("age", "18");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
builder.queryParams(params);
// 使用 builder.build().toUriString() 防止中文乱码。
// 如果直接builder.toUriString()会中文乱码
return restTemplate.getForObject(builder.build().toUriString(), String.class);
}
方式2: 直接拼接到URL
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData?name=小西&age=18";
return restTemplate.getForObject(url, String.class);
}
方式3: 使用占位符
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData?name={name}&age={age}";
Map map = new HashMap<>();
map.put("name", "小南");
map.put("age", "18");
return restTemplate.getForObject(url, String.class, map);
}
或
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData?name={name}&age={age}";
return restTemplate.getForObject(url, String.class, "小红", "21");
}
调用和 getForObject类似, 但可以从getForEntiy获取更多的响应数据
客户端:
@GetMapping("/getData")
public Object getData() {
String url = "http://localhost:8060/getData?name={name}&age={age}";
ResponseEntity entity = restTemplate.getForEntity(url, String.class, "小男", "18");
HttpStatus statusCode = entity.getStatusCode();
String body = entity.getBody();
int statusCodeValue = entity.getStatusCodeValue();
HttpHeaders headers = entity.getHeaders();
return "statusCode:"+statusCode+", statusCodeValue:"+statusCodeValue+", body"+body+" , headers:"+headers;
}
客户端:
@GetMapping("/getData")
public Object getData() throws UnsupportedEncodingException {
String url = "http://localhost:8060/getData";
MultiValueMap params = new LinkedMultiValueMap<>();
params.add("name", "小小");
params.add("age", "18");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
builder.queryParams(params);
// builder.toUriString()会中文乱码
// 可以使用 URLDecoder 对其进行编码
String decode = URLDecoder.decode(builder.toUriString(), "utf-8");
return restTemplate.getForObject(decode, String.class);
}
使用 exchange 方法发送get请求
服务端:
@GetMapping("/getData")
public Object getData(HttpServletRequest request, String name, String age) {
String token = request.getHeader("token");
return "收到数据:token: +"+token+" ,name:"+name+", age:"+age;
}
客户端:
@GetMapping("/getData")
public Object getData() throws UnsupportedEncodingException {
String url = "http://localhost:8060/getData?name={name}&age={age}";
HttpHeaders headers = new HttpHeaders();
headers.add("token","123456");
HttpEntity request = new HttpEntity<>(headers);
return restTemplate.exchange(url, HttpMethod.GET, request, String.class, "小男", "18");
}
服务端:
@PostMapping("/getData")
public Object getData() {
return "收到数据";
}
客户端:
String url = "http://localhost:8060/getData";
restTemplate.postForObject(url, null, String.class);
服务端:
@PostMapping("/getData")
public Object getData(Student student) {
return "收到数据:name:"+student.getName()+", age:"+student.getAge();
}
客户端:
String url = "http://localhost:8060/getData";
MultiValueMap map = new LinkedMultiValueMap<>();
map.add("name", "小明");
map.add("age", "20");
restTemplate.postForObject(url, map, String.class);
服务端:
@PostMapping("/getData")
public Object getData(@RequestBody Student student) {
return "收到数据:name:"+student.getName()+", age:"+student.getAge();
}
客户端:
String url = "http://localhost:8060/getData";
Student student = new Student();
student.setName("小明");
student.setAge(5);
restTemplate.postForObject(url, student, String.class);
或
String url = "http://localhost:8060/getData";
Map map = new HashMap<>();
map.put("name", "小红");
map.put("age", "18");
restTemplate.postForObject(url, map, String.class);
和 postForObject类似
服务端:
@PostMapping("/getData")
public Object getData(HttpServletRequest request, Student student) {
String token = request.getHeader("token");
return "收到数据:token: "+token+", name:"+student.getName()+", age:"+student.getAge();
}
客户端:
String url = "http://localhost:8060/getData";
// 请求参数
MultiValueMap map = new LinkedMultiValueMap<>();
map.add("name", "小明");
map.add("age", "20");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(map,headers);
// 发送请求
restTemplate.postForObject(url, httpEntity, String.class);
或
String url = "http://localhost:8060/getData";
// 请求参数
MultiValueMap map = new LinkedMultiValueMap<>();
map.add("name", "小明");
map.add("age", "20");
// 组装url 和 请求参数
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
builder.queryParams(map);
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(headers);
// 发送请求
restTemplate.postForObject(builder.build().toUriString(), httpEntity, String.class);
服务端:
@PostMapping("/getData")
public Object getData(HttpServletRequest request,@RequestBody Student student) {
String token = request.getHeader("token");
return "收到数据:token: "+token+", name:"+student.getName()+", age:"+student.getAge();
}
客户端:
String url = "http://localhost:8060/getData";
// 请求参数
Student student = new Student();
student.setName("小欧");
student.setAge(5);
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(student, headers);
// 发送请求
return restTemplate.postForObject(url, httpEntity, String.class);
或
String url = "http://localhost:8060/getData";
// 请求参数
Map map = new HashMap<>();
map.put("name", "小明");
map.put("age", "20");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(map,headers);
// 发送请求
restTemplate.postForObject(url, httpEntity, String.class);
restTemplate调用时,当响应的状态码非200 (401,500等)均会以异常的形式抛出。 可通过 HttpClientErrorException 获取body。
服务端:
// 响应的状态码设置为400
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@GetMapping("/getData")
public Object getData() {
return "接口异常了";
}
客户端:
String url = "http://localhost:8060/getData";
// 转态码
int code = 0;
// body
String body = "";
try {
ResponseEntity result = restTemplate.getForEntity(url, String.class);
} catch (HttpClientErrorException e) {
code = e.getStatusCode().value();
body = e.getResponseBodyAsString();
}