给请求加上头信息
Request request = new Request();
HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("accept", "application/json"); requestHeaders.add("content-type", "application/json"); requestHeaders.add("content-length", "256"); requestHeaders.add("authorization", authorization); requestHeaders.setContentType(MediaType.APPLICATION_JSON)
HttpEntity<?> httpEntity = new HttpEntity<Object>(request, requestHeaders);
ResponseEntity<Response> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Response.class);
return response.getBody();
有些请求是键值对的形式,用request的方法或封装HttpEntity也传不进去参数,可以尝试用下面的方法:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("shortcut", shortcut); map.add("_api_key", apikey);
DefaultResponse response = restTemplate.postForObject(url, map, DefaultResponse.class);
从远程获取的list用resttemplate转成相应的对象
ObjectMapper mapper = new ObjectMapper(); DefaultResponse defaultResponse = rehabilitationProxy.getServiceDate(); List<Resource> resources = (List<Resource>) defaultResponse.getData(); for (int i = 0; i < resources.size(); i++) { Resource resource = mapper.convertValue(resources.get(i), Resource.class); }