传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。
使用restTemplate访问restful接口非常的简单粗暴无脑。(url, requestMap, ResponseBean.class)这三个参数分别代表:请求地址、请求参数、HTTP响应报文被转换成的对象类型。
RestTemplate方法的名称遵循命名约定,第一部分指出正在调用什么HTTP方法,第二部分指示返回的内容。本例中调用了restTemplate.postForObject方法,post指调用了HTTP的post方法,Object指将HTTP响应转换为您选择的对象类型。还有其他很多类似的方法,有兴趣的同学可以参考官方api。
一、创建RestTemplateConfig配置类
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//ms
factory.setConnectTimeout(15000);//ms
return factory;
}
}
创建实体Bean用于数据传递
public class TestEntity {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestEntity{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
二、模拟Rest被调用接口
@RestController
public class TestController {
@GetMapping("testGet")
public TestEntity testGet() {
TestEntity testEntity = new TestEntity();
testEntity.setId(1);
testEntity.setName("get");
return testEntity;
}
@PostMapping("testPost")
public TestEntity testPost(){
TestEntity testEntity = new TestEntity();
testEntity.setId(1);
testEntity.setName("post");
return testEntity;
}
@PostMapping("testPostParam")
public String testPostParam(@RequestParam("id") String id,@RequestParam("name") String name){
System.out.println("Post id:"+id);
System.out.println("Post name:"+name);
return "post succ";
}
@PutMapping("testPut")
public String testPut(@RequestParam("id") String id,@RequestParam("name") String name){
System.out.println("put id:"+id);
System.out.println("put name:"+name);
return "del succ";
}
@DeleteMapping("testDel")
public String testDel(@RequestParam("id") String id){
System.out.println("del id:"+id);
return "del succ";
}
}
三、创建使用RestTemplate调用Rest接口服务层
@Service
public class RunService {
@Autowired
private RestTemplate restTemplate;
private static String GET_URL = "http://localhost:8080/testGet";
private static String POST_URL = "http://localhost:8080/testPost";
private static String POST_PARAM_URL = "http://localhost:8080/testPostParam";
private static String PUT_URL = "http://localhost:8080/testPut";
private static String DEL_URL = "http://localhost:8080/testDel";
/**
* 调用Get接口
* 实现了三种方式调用
*/
public void getTestGet() throws URISyntaxException {
//1、通过getForObject()调用
TestEntity testEntity1 = this.restTemplate.getForObject(GET_URL, TestEntity.class);
System.out.println("get testEntity1:"+testEntity1);
//测试结果
get testEntity1:TestEntity{id=1, name='get'}
//2、通过getForEntity()调用
ResponseEntity<TestEntity> responseEntity1 = this.restTemplate.getForEntity(GET_URL, TestEntity.class);
HttpStatus statusCode = responseEntity1.getStatusCode();
HttpHeaders header = responseEntity1.getHeaders();
TestEntity testEntity2 = responseEntity1.getBody();
System.out.println("get testEntity2:"+testEntity2);
System.out.println("get statusCode:"+statusCode);
System.out.println("get header:"+header);
//测试结果
get testEntity2:TestEntity{id=1, name='get'}
get statusCode:200
get header:{Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Tue, 24 Apr 2018 07:22:52 GMT]}
//3、通过exchange()调用
RequestEntity requestEntity = RequestEntity.get(new URI(GET_URL)).build();
ResponseEntity<TestEntity> responseEntity2 = this.restTemplate.exchange(requestEntity, TestEntity.class);
TestEntity testEntity3 = responseEntity2.getBody();
System.out.println("get testEntity3:"+testEntity3);
//测试结果
get testEntity3:TestEntity{id=1, name='get'}
}
/**
* 调用Post接口
* 实现了三种方式调用
*/
public void getTestPost() throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
String data = new String();
HttpEntity<String> formEntity = new HttpEntity<String>(data, headers);
//1、通过postForObject()调用
TestEntity testEntity1 = this.restTemplate.postForObject(POST_URL,formEntity, TestEntity.class);
System.out.println("post testEntity1:"+testEntity1);
//测试结果
post testEntity1:TestEntity{id=1, name='post'}
//2、通过postForEntity()调用
ResponseEntity<TestEntity> responseEntity1 = this.restTemplate.postForEntity(POST_URL, formEntity,TestEntity.class);
HttpStatus statusCode = responseEntity1.getStatusCode();
HttpHeaders header = responseEntity1.getHeaders();
TestEntity testEntity2 = responseEntity1.getBody();
System.out.println("post testEntity2:"+testEntity2);
System.out.println("post statusCode:"+statusCode);
System.out.println("post header:"+header);
//测试结果
post testEntity2:TestEntity{id=1, name='post'}
post statusCode:200
post header:{Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Tue, 24 Apr 2018 07:22:52 GMT]}
//3、通过exchange()调用
RequestEntity requestEntity = RequestEntity.post(new URI(POST_URL)).body(formEntity);
ResponseEntity<TestEntity> responseEntity2 = this.restTemplate.exchange(requestEntity, TestEntity.class);
TestEntity testEntity3 = responseEntity2.getBody();
System.out.println("post testEntity3:"+testEntity3);
getTestPut succ
//测试结果
post testEntity3:TestEntity{id=1, name='post'}
}
/**
* 调用Post接口,并传递了参数
*/
public void getTestPostParam(){
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("id", "100");
map.add("name", "getTestPostParam");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
String data = restTemplate.postForObject(POST_PARAM_URL,request,String.class);
System.out.println("getTestPostParam data: "+ data);
System.out.println("getTestPostParam succ");
//测试结果
getTestPostParam data: post succ
}
/**
* 调用Put接口
*/
public void getTestPut(){
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("id", "101");
map.add("name", "getTestPut");
restTemplate.put(PUT_URL,map);
System.out.println("getTestPut succ");
//测试结果
getTestPostParam succ
}
/**
* 调用Del接口
*/
public void getTestDel(){
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("id", "101");
map.add("name", "getTestPut");
restTemplate.delete(DEL_URL,map);
//测试结果
getTestPut succ
}
}
四、开发中的例子:
@Transactional(rollbackFor = Exception.class)
public void syncPersonFromHR(List<Person> personList) {
//用于获取人员信息
Map<String, Person> personMap = new HashMap<>();
personList.stream().forEach(person -> {
personMap.put(person.getJobNumber(), person);
});
List<Person> pers = new ArrayList<>();
//请求链接
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
//通过api请求新增或修改人员
ResponseEntity<JsonResult> result = client.postForEntity(hrPersonUrl, entity, JsonResult.class);
//http请求是否成功
boolean requestSuccess = result.getStatusCode().equals(HttpStatus.OK);
if(requestSuccess){
//获取查询的信息
JsonResult jsonResult = result.getBody();
if(jsonResult != null && jsonResult.getCode() == 0) {
JSONArray array = JSONArray.fromObject(jsonResult.getData());
array.stream().forEach(o -> {
JSONObject object = (JSONObject) o;
//根据工资号判断人员是否存在
Person person = personMap.get(object.getString("jobNumber"));
if (person == null) {
person = new Person();
}
Person per = JsonUtils.jsonToPojo(object.toString(), Person.class);
//更新人员信息
BeanUtils.copyProperties(per, person, "id", "perType", "perTypeName", "version","openvpn","opendc");
pers.add(person);
});
personRepository.saveAll(pers);
LOGGER.info("新增修改人员总数为:" + pers.size());
}
} else {
LOGGER.info("连接HR系统失败,人员同步失败");
}
}
网友评论