在服务端使用java语言,向远程接口发起请求,得到响应数据的方法。实现远程接口调用方法很多,这里我们使用spring封装的工具类RestTemplate,使用起来最方便简单。
1 发起get请求
@Test
public void getForObject(){
//依赖jackson组件,把响应体的json数据转为指定对象:String对象
RestTemplate t = new RestTemplate();
//https://www.tianapi.com/
String url="https://apis.tianapi.com/toutiaohot/index?key=ed475d5faa4488028e9f5e369c77e1b5";
String forObject = t.getForObject(url, String.class);
}
@Test
public void getForObjectUriValiables(){
//依赖jackson组件,把响应体的json数据转为指定对象:AxiosResult对象
String url="http://localhost:8080/user/{0}";
RestTemplate t = new RestTemplate();
AxiosResult forObject = t.getForObject(url, AxiosResult.class,"2");
System.out.println(forObject);
}
@Test
public void getForEntity(){
//getForEntity可以获取响应头,响应体
String url="http://localhost:8080/user/{0}";
RestTemplate t = new RestTemplate();
ResponseEntity<String> resp = t.getForEntity(url, String.class);
String body = resp.getBody();//响应体
HttpHeaders headers = resp.getHeaders();//响应头
}
2 发起post请求
@GetMapping("/test1")
public ResponseEntity test1(){
String url = "http://192.168.21.178:8888/book/add";
MultiValueMap<String, Object> test= new LinkedMultiValueMap<String, Object>();
test.add("bookId",1111);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(test, headers);
ResponseEntity<String> s = restTemplate.postForEntity(url, request, String.class);
System.out.println(s.getBody());
return ResponseEntity.ok(AxiosResult.suc());
}
@GetMapping("/test1")
public ResponseEntity test1(){
String url = "http://192.168.21.178:8888/book/add";
MultiValueMap<String, Object> test= new LinkedMultiValueMap<String, Object>();
test.add("bookId",1111);//?bookId=1111
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(test, headers);
String s = restTemplate.postForObject(url,request,String.class);
System.out.println(s);
return ResponseEntity.ok(AxiosResult.suc());
}
3 发起put请求
@Test
public void put(){
//put方法,无返回值
String url="http://localhost:8080/role";
Map<String,String> map = new HashMap<>();
map.put("id","1");
map.put("rname","测试修改角色名");
RestTemplate t = new RestTemplate();
t.put(url, map);
}
4 发起delete请求
@Test
public void del(){
//无返回值
String url="http://localhost:8080/role/{0}";
RestTemplate t = new RestTemplate();
t.delete(url,"3,4");
}
5 通用方法
//可以设置请求头,请求体,请求方法;可以获取响应头,响应体
@Test
public void exchange(){
String url="http://localhost:8080/role";
Role r = new Role();
r.setRname("aaaa");
r.setRdesc("bbbb");
RestTemplate t = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("admin_token","asdfasdfasdf");
HttpEntity req = new HttpEntity(r,headers);
ResponseEntity<String> resp = t.exchange(url, HttpMethod.POST, req, String.class);
String body = resp.getBody();
HttpHeaders headers1 = resp.getHeaders();
}