1.。。。RestTemplate是spring的一个rest客户端,在spring-web这个包下,spring boot的依赖如下
org.springframework.boot
spring-boot-starter-web
导入json解析依赖 此依赖是发送post请求时将对象转化的
net.sf.json-lib
json-lib
2.4
jdk15
2.。。。在配置类中配置restTemplate 此处设置了连接超时时间和读取的超时时间
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
// 设置超时
requestFactory.setConnectTimeout(60000);
requestFactory.setReadTimeout(60000);
//利用复杂构造器可以实现超时设置,内部实际实现为 HttpClient
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
3.然后在需要用到的类中注入
@Autowired
private RestTemplate restTemplate;
//设置请求头的编码格式
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//请求的实体
ClientTokenVM clientTokenVM = new ClientTokenVM();
clientTokenVM.setToken(publishBean.getToken());
//将实体转换成json对象(好像是必须转的,不转就各种报错啊 一下午)
JSONObject jsonObj = JSONObject.fromObject(clientTokenVM);
HttpEntity formEntity = new HttpEntity<>(jsonObj.toString(), headers);
//调用api接口获取新的token(请求路径加在配置文件中)
String tokenInfo = restTemplate.postForObject("url", formEntity, String.class);
JSONObject jsonObject = JSONObject.fromObject(tokenInfo);
if (jsonObject != null && Boolean.TRUE.equals(jsonObject.get("success"))) {
//取出新的token
String newToken = jsonObject.getString("data");
}
有时候发送post请求可以会传map类型的参数 此时应该 用new LinkedMultiValueMap<>();
HttpHeaders reqHeaders = new HttpHeaders();
reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap formParams = new LinkedMultiValueMap<>();//此处用这个
formParams.set("grant_type", "client_credentials");
addAuthentication(reqHeaders);
HttpEntity> entity = new HttpEntity<>(formParams, reqHeaders);
log.debug("contacting OAuth2 token endpoint to authenticate internal service.");
ResponseEntity responseEntity = restTemplate.postForEntity(tokenUrl, entity,
OAuth2AccessToken.class);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
log.debug("failed to authenticate user with OAuth2 token endpoint, status: {}",
responseEntity.getStatusCodeValue());
throw new HttpClientErrorException(responseEntity.getStatusCode());
}
OAuth2AccessToken accessToken = responseEntity.getBody();
String jsonResult = restTemplate.getForEntity(url, String.class).getBody();
//将返回结果搞成json 然后从json中取数据
JSONObject jsonObject = JSONObject.fromObject(jsonResult);
利用此请求可以轻松在post和get请求间切换
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, accessToken.getValue()));
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
SearchNameVM searchNameVM = new SearchNameVM(name);
JSONObject jsonObj = JSONObject.fromObject(searchNameVM);
HttpEntity requestEntity = new HttpEntity<>(jsonObj.toString(), headers);
//3.请求base接口获取数据baseUrl + BASE_URI
ResponseEntity response = restTemplate.exchange(baseUrl, HttpMethod.POST, requestEntity, List.class);
if (response.getStatusCode().is2xxSuccessful()) {
List body = response.getBody();
//4.将租户id和名称组装返回
List resultList = Lists.newArrayList();
body.stream().forEach(e -> {
TanentInfoViewEntity tanentInfoViewEntity = new TanentInfoViewEntity((String) e.get("tenantId"), (String) e.get("tenantName"));
resultList.add(tanentInfoViewEntity);
});
return resultList;
}
此例子是我从另一个微服务发送post请求返回的list数据里边放的是map类型 将其取出来 放到新对象 将对象装进集合的操作
在很多场景中我们需要异步调用,我们使用RestTemplate的兄弟类AsyncRestTemplate。 AsyncRestTemplate是在Spring4.0中对RestTemplate进行扩展产生的新类,其为客户端提供了异步http请求处理的一种机制,通过返回ListenableFuture对象生成回调机制,以达到异步非阻塞发送http请求。
public String asyncReq(){
String url = "http://localhost:8080/jsonAsync";
ListenableFuture> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
future.addCallback(new SuccessCallback>() {
public void onSuccess(ResponseEntity result) {
System.out.println(result.getBody().toJSONString());
}
}, new FailureCallback() {
public void onFailure(Throwable ex) {
System.out.println("onFailure:"+ex);
}
});
return "this is async sample";
}