本文主要是介绍关于 spring RestTemplate restful,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
API 地址:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
客户端 spring xml 转换器配置:
<bean id="ky.requestFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory"><property name="readTimeout" value="10000"/><property name="connectTimeout" value="5000"/></bean><bean id="restTemplate" class="org.springframework.web.client.RestTemplate"><constructor-arg ref="ky.requestFactory"/><property name="messageConverters"><list><bean class="org.springframework.http.converter.FormHttpMessageConverter"></bean><bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"></bean><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean><bean class="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes"><list><value>application/json;charset=UTF-8</value></list></property></bean></list></property></bean>
客户端代码
@AutowiredRestTemplate restTemplate;//final String SERVICE_NAME = "chat-ai-service";final String SERVICE_NAME = "localhost:8011";//@HystrixCommand(fallbackMethod = "fallbackSearchAll")public User readUserInfo(User user) {String url="http://" + SERVICE_NAME + "/sys/user/getByEntity";User user2=restTemplate.postForObject(url,getHeaderJsonUtf8(user), User.class);return user2;}
/***header "Content-Type", "application/json;charset=UTF-8"* @param object* @return*/public static HttpEntity<?> getHeaderJsonUtf8(Object object){MultiValueMap<String, String> headers=new LinkedMultiValueMap<>();headers.add("Content-Type", "application/json;charset=UTF-8");HttpEntity<?> bentity = new HttpEntity<>(object, headers);return bentity;}
服务端 代码:
/*** 获取单条数据* @param entity* @return*/@ResponseBody@RequestMapping(value = {"getByEntity"})public User getByEntity(@RequestBody User entity) {return service.get(entity);}
注意
post 方式也可以在url中加参数
Url中参数的匹配问题
(1)参数为Map 类型
postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)
url中参数没有顺序,根据key去匹配
public User readUserInfo() {String url="http://localhost/aa?name={name}&id={id}";Map<String,String> map=new HashMap<String,String>();map.put("id", "123");map.put("name", "张三");User user2=restTemplate.getForObject(url, User.class, map);return user2;}
(2)参数为 Object... uriVariables类型
patchForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
url 中的参数是根据Object... uriVariables中参数的顺序去匹配的,所以顺序不要弄错了
public User readUserInfo() {String url="http://localhost/aa?name={id}&id={name}";User user2=restTemplate.getForObject(url, User.class, "id123","name张三");return user2;}
一些请求传参方式:
@Component
public class RESTClient {@Autowiredprivate RestTemplate template;private final static String url = "http://localhost:8080/SpringRestWS/restful/";public String show() {return template.getForObject(url + "show.do", String.class, new String[]{});}public String getUserById(String id) {return template.getForObject(url + "get/{id}.do", String.class, id); }public String addUser(String user) {return template.postForObject(url + "add.do?user={user}", null, String.class, user);}public String editUser(String user) {template.put(url + "edit.do?user={user}", null, user);return user;}public String removeUser(String id) {template.delete(url + "/remove/{id}.do", id);return id;}
}
错误问题:
1、List<T> 类型转换错误
下面的代码会报 ClassCastException: RestTemplate returning List<LinkedHashMap> instead of List<MymodelClass>
RestTemplate restTemplate=new RestTemplate();String url="http://localhost:8011/aichat/aiWorkOrder/findList";List<AiWorkOrder> list=(List<AiWorkOrder>)restTemplate.postForObject(url,entity,new ArrayList<AiWorkOrder>().getClass());AiWorkOrder order=list.get(0);
解决办法:
1. 转为数组,然后在转为list
AiWorkOrder[] myModelClasses = restTemplate.postForObject(url,entity, AiWorkOrder[].class);
List<AiWorkOrder> as=Arrays.asList(myModelClasses);
2、
ParameterizedTypeReference<List<AiWorkOrder>> typeRef = new ParameterizedTypeReference<List<AiWorkOrder>>() {
};
ResponseEntity<List<AiWorkOrder>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(mvm), typeRef);
List<AiWorkOrder> myModelClasses = responseEntity.getBody();
这篇关于关于 spring RestTemplate restful的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!