dw怎么做网站注册登入页面,贵州城乡住房建设网站,网站的扁平化设计理念,女性门户网站源码RestTemplate是Spring提供的用于访问Rest服务的客户端#xff0c;RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
一、使用Get进行访问
1、获取json格式 使用 getForEntity() API 发起 GET 请求#xff1a;
RestTemplate restTemplate… RestTemplate是Spring提供的用于访问Rest服务的客户端RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
一、使用Get进行访问
1、获取json格式 使用 getForEntity() API 发起 GET 请求
RestTemplate restTemplate new RestTemplate();String fooResourceUrl http://localhost:8080/spring-rest/foos;ResponseEntityString response restTemplate.getForEntity(fooResourceUrl /1, String.class);System.out.println(response.getStatusCode()); 可以访问完整的 HTTP 响应因此可以检查 HTTP 状态码是否成功或者处理响应体
ObjectMapper mapper new ObjectMapper();
JsonNode root mapper.readTree(response.getBody());
JsonNode name root.path(name);
System.out.println(name.asText()); 如上将响应体作为标准字符串String返回并使用 Jackson以及 Jackson 提供的 JSON 节点结构来验证一些细节。
2、获取pojo格式 可以将响应直接映射到资源 DTO
public class Foo implements Serializable {private long id;private String name;// 标准的 get 、set 方法
} 只需要调用 template 的 getForObject API 即可
Foo foo restTemplate.getForObject(fooResourceUrl /1, Foo.class);
Assertions.assertNotNull(foo.getName());
Assertions.assertEquals(foo.getId(), 1L);
二、使用Post进行访问
1、传递表单参数 可以使用 postForLocation()、postForObject() 或 postForEntity() 方法 在 API 中创建新资源。前者postForLocation返回新创建资源的 URI后者返回资源本身。 // 创建请求头对象HttpHeaders headers new HttpHeaders();// 设置请求内容类型 表单上传编码格式为application/x-www-form-urlencodedheaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);// 请求携带的参数与对应的值MultiValueMapString, String map new LinkedMultiValueMap();map.add(username, USER_NAME);map.add(password, PASSWORD);// HttpEntity表示http的request和resposne实体它由消息头和消息体组成。// 从HttpEntity中可以获取http请求头和回应头也可以获取http请求体和回应体信息。HttpEntityMultiValueMapString, String request new HttpEntity(map, headers);return restTemplate.postForObject(TOKEN_URL, request, ComplainWorkToken.class);
2、传递json参数 HttpHeaders headers new HttpHeaders();// 设置请求头是jsonheaders.add(Content-Type, MediaType.APPLICATION_JSON_UTF8_VALUE);// 携带的json参数格式MapString, Object map2 new HashMap();map2.put(pageNo, pageNo);map2.put(pageSize, pageSize);map2.put(endTime, endTime);map2.put(startTime, startTime);HttpEntityMapString, Object httpEntity new HttpEntity(map2, headers);ComplainWorkResponse complainWorkResponse restTemplate.postForObject(url, httpEntity, ComplainWorkResponse.class);assert complainWorkResponse ! null;return complainWorkResponse.getComplainWorkData().getList();