RestTemplate的使用
1,直接调用会错,表示没有没定义bean
@Autowired private RestTemplate restTemplate
//会报 Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
2,需要在config注入bean
@LoadBalanced @Bean public RestTemplate loadBalanced1() { return new RestTemplate(); } 这样也会报错,他会在服务注册中心找,找不到实例No instances available for xxx
3,解决办法,
在配置类 */ @Configuration public class RestConfig { @Bean(name = "remoteRestTemplate") public RestTemplate restTemplateRemote() { return new RestTemplate(); } } 在需要调入的 @Autowired @Qualifier(value = "remoteRestTemplate") private RestTemplate rest; 使用方法 //1、构建body参数 JSONObject jsonObject = new JSONObject(); jsonObject.put("UserName",USER_NAME); jsonObject.put("Password",PASS_WORD); //2、添加请求头 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type","application/json"); //3、组装请求头和参数 HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(jsonObject), headers); //4、发起post请求 ResponseEntity<String> stringResponseEntity = null; try { stringResponseEntity = restTemplate.postForEntity(URL, formEntity, String.class); log.info("ResponseEntity----"+stringResponseEntity); } catch (RestClientException e) { e.printStackTrace(); } //5、获取http状态码 int statusCodeValue = stringResponseEntity.getStatusCodeValue(); log.info("httpCode-----"+statusCodeValue); //6、获取返回体 String body = stringResponseEntity.getBody(); log.info("body-----"+body); //7、映射实体类 Wrapper wrapper = JSONObject.parseObject(body, Wrapper.class); String data = wrapper.getData(); log.info("data-----"+data);
4.处理响应参数
//如果响应结果为多层,可以转换为jsonnode
ObjectMaper mapper=new ObjectMapper();
JSONNode jsonnode= mapper.readTree(Stringjson);
jsonNode path=jsonnode.path(“data”).path("records");//可以链式获取多层关系
for(JsonNOde node:path){ //如果path是数组可以for循环
mapper.treeToValue(node,your Class); //可以转换映射到实体类
}
5实体创建映射关系
使用@Jsonproperty("sxxx-xx) 可以做映射关系
private String nama;
在类上加注解@JSONIgnoreProperties(IgnoreUnknown=true) 实体类可以多一些不用对应的属性字段
public class 类名{}
2使用@JSONField注解
@JSONField(name = "Field")

浙公网安备 33010602011771号