RestTemplate
承灿 2023/12/28
# 注入RestTemplate
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
# GetForEntity方法
package com.cc.resttemplate.controller;
import com.cc.resttemplate.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* @author: lichengcan
* @date: 2023-12-28 11:27
* @description GetForEntity
**/
@RestController
@RequestMapping(value = "/getForEntity")
public class GetForEntityController {
@Autowired
RestTemplate restTemplate;
/**
* 使用键值对的形式
*/
@GetMapping("/userKeyValue")
public User userKeyValue(@RequestParam Long id, @RequestParam String name) {
return restTemplate.getForEntity("http://localhost:8080/userKeyValue?id={id}&name={name}", User.class, id,name).getBody();
}
/**
* 使用Map的形式
*/
@GetMapping("/userByMap")
public User userByMap(@RequestParam Long id, @RequestParam String name) {
Map<String, Object> requestParams = new HashMap<>(2);
requestParams.put("id", id);
requestParams.put("name", name);
return restTemplate.getForEntity("http://localhost:8080/userKeyValue?id={id}&name={name}", User.class, requestParams).getBody();
}
/**
* 无请求参数
* @return
*/
@GetMapping("/userNoRequestParam")
public User userNoRequestParam() {
return restTemplate.getForEntity("http://localhost:8080/userKeyValue", User.class).getBody();
}
}
# Exchange方法
package com.cc.resttemplate.controller;
import com.cc.resttemplate.domain.User;
import com.cc.resttemplate.domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* @author: lichengcan
* @date: 2023-12-28 11:52
* @description exchange
**/
@RestController
@RequestMapping("/exchange")
public class ExchangeController {
@Autowired
RestTemplate restTemplate;
@GetMapping("/getUserKeyValue")
public User getUserKeyValue(Integer id, String name) {
final String url = "http://localhost:8080/userKeyValue?id={id}&name={name}";
return restTemplate.exchange(url, HttpMethod.GET, null, User.class, id, name).getBody();
}
@PostMapping("/getUserDomain")
public User getUserDomain(@RequestBody(required = false) User user) {
String url = "http://localhost:8080/userDomain";
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("cc", "小灿12345");
HttpEntity<User> request = new HttpEntity<>(user, headers);
return restTemplate.exchange(url, HttpMethod.POST, request, User.class).getBody();
}
@PostMapping("/getUsersDomain")
public Users getUsersDomain() {
String url = "http://localhost:8080/usersDomain";
//请求参数
Users users = new Users();
Map<String, Object> user = new HashMap<>(2);
user.put("param1", "xxcan");
user.put("param2", "xx12345");
users.setId(12345L);
users.setMap(user);
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("cc", "小灿");
HttpEntity<Users> request = new HttpEntity<>(users,headers);
return restTemplate.exchange(url, HttpMethod.POST, request, Users.class).getBody();
}
@PostMapping("/getUserMap")
public Map getUserMap() {
String url = "http://localhost:8080/userMap";
//请求参数
Map<String, Object> users = new HashMap<>(2);
Map<String,Object> user = new HashMap<>(2);
user.put("name","灿灿");
user.put("id",555L);
users.put("param1", "xxcan");
users.put("param2", "xx12345");
users.put("user",user);
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("cc", "小灿");
HttpEntity<Map> request = new HttpEntity<>(users,headers);
return restTemplate.exchange(url, HttpMethod.POST, request, Map.class).getBody();
}
}
上面使用POST时会报错HttpClientErrorException 的 UnsupportedMediaType 错误。该错误表示请求的媒体类型不受支持。服务器返回了状态码 415(Unsupported Media Type)
解决在header中添加:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
# GetForObject方法
package com.cc.resttemplate.controller;
import com.cc.resttemplate.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
/**
* @author: lichengcan
* @date: 2023-12-28 10:38
* @description GetForObject
**/
@RestController
@RequestMapping("/getForObject")
public class GetForObjectController {
@Autowired
RestTemplate restTemplate;
/**
* 1 传入一个值,返回一个对象的情况:
* (列举了常用的,没有面面俱到,可以照猫画虎)
* 1.1 直接将变量写在 url 中,记得添加注解 @PathVariable
* 参数拼接在url上
*
* @param id
* @return
*/
@GetMapping("/findUserById/{id}")
public User findUserById(@PathVariable Integer id) {
String url = "http://localhost:8080/user/";
return restTemplate.getForObject(url + id, User.class);
}
/**
* 1.2 将变量通过key=word形式传递,
* 通过 HttpServletRequest 获取参数
* 地址栏 key=value 形式传参
*
* @param request
* @return
*/
@GetMapping("/findAUser")
public User findAUser(HttpServletRequest request) {
String id = request.getParameter("id");
String url = "http://localhost:8080/userKeyValue?id=";
return restTemplate.getForObject(url + id, User.class);
}
/**
* 1.3 通过占位符:
* 参数的不同传法 数字占位符
*
* @param id
* @return
*/
@GetMapping("/findOneUser/{id}")
public User findOneUser(@PathVariable Integer id) {
String url = "http://localhost:8080/user/{0}";
return restTemplate.getForObject(url, User.class, id);
}
/**
* 1.4 通过占位符,结合 Map:
* 参数的不同传法,Map类型
* 花括号里面的名字值和 map 的键名字保持一致即可,就可以传递对应的值。
* @param id
* @return
*/
@GetMapping("/one/{id}")
public User findOneUser(@PathVariable Long id) {
Map<String, Long> map = new HashMap<String, Long>(2);
map.put("id", id);
return restTemplate.getForObject("http://localhost:8080/user/{id}", User.class, map);
}
/**
* 1.5 通过 URI 进行 访问:
* 使用 Spring 的 UriComponents 工具,参数可以整合到路径中。
* @param request
* @return
*/
@GetMapping("/req")
public User findAUser1(HttpServletRequest request) {
Integer id = request.getParameter("id") == null ? 1 : Integer.valueOf(request.getParameter("id"));
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://localhost:8080/userKeyValue?id=" + id).
build().encode();
URI uri = uriComponents.toUri();
return restTemplate.getForObject(uri, User.class);
}
/**
* 1.6 通过 append 拼接
* @param id
* @return
*/
@GetMapping("/req1")
public User findAUser2(Integer id) {
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://localhost:8080/userKeyValue?id={id}").
build().expand(id).encode();
URI uri = uriComponents.toUri();
return restTemplate.getForObject(uri, User.class);
}
}
# 测试demo-被调用方
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cc.userdemo.controller;
import com.cc.userdemo.domain.User;
import com.cc.userdemo.domain.Users;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* @author lichengcan
*/
@RestController
@RequestMapping()
public class UserController {
@GetMapping("/user/{id}")
public User user(@PathVariable Long id) {
User user = new User();
user.setId(id);
user.setName("cc");
user.setAge(18);
return user;
}
@GetMapping("/userKeyValue")
public User userKeyValue(@RequestParam(required = false) Long id,
@RequestParam(required = false) String name) {
User user = new User();
user.setId(id == null ? 1 : id);
user.setName(name == null ? "cc" : name);
user.setAge(18);
return user;
}
@PostMapping("/userDomain")
public User userDomain(@RequestBody(required = false) User user, HttpServletRequest request) {
user.setAge(188);
//å°ç¿乱码了
try {
System.out.println(new String(request.getHeader("cc").getBytes("ISO-8859-1"), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return user;
}
@PostMapping("/usersDomain")
public Users usersDomain(@RequestBody(required = false) Users user, HttpServletRequest request) {
try {
System.out.println(new String(request.getHeader("cc").getBytes("ISO-8859-1"), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return user;
}
@PostMapping("/userMap")
public Map userMap(@RequestBody(required = false) Map user, HttpServletRequest request) {
try {
System.out.println(new String(request.getHeader("cc").getBytes("ISO-8859-1"), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return user;
}
}
# User
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
# Users
@Data
public class Users {
private Long id;
private String name;
private Integer age;
private Map map;
}