SpringBoot-RestTemplate

摘要

SpringBoot提供RestTemplate作为Rest请求访问的客户端

使用

GET请求

1 获取对象

public User findById(Long id){
    return restTemplate.getForObject("http://localhost:8080/"+id,User.class)
}

2 获取数组

public List<User> getUsers(){
    return Arrays.asList(restTemplate.getForObject("http://localhost:8080/list".User[].class));
}

3 GET请求带有参数

public User[] find(String name,int age){
    Map<String,Object> param = Maps.newHashMap();
    param.put("name",name);
    param.put("age",age);
    return restTemplate.getForObject(
        "http://localhost:8080/serach?name={name}&age={age}",
        User[].class,
        param)
}

4 请求文件

String url = "";
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> request = new HttpEntity<>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, request, byte[].class);
byte[] bytes = response.getBody();

POST请求

1 请求携带cookie

String url= "";
HttpHeaders headers = new HttpHeaders();
List<String> cookies = new ArrayList<>();
cookies.add("mycookie=mycookie");
headers.put(HttpHeaders.COOKIE, cookies);
HttpEntity request = new HttpEntity(null, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

2 模拟提交表单

String url = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add("username", "admin");
form.add("password", "admin");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); 

3 模拟提交json

String url = "";
String json = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
HttpEntity<String> request = new HttpEntity<>(json, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

4 通过URL提交POST请求

String url = "http://localhost:8080/login?username={0}&password={1}";
url = MessageFormat.format(url, "admin", "admin");
restTemplate.postForEntity(url, null, String.class);

猜你喜欢

转载自blog.csdn.net/weixin_38229356/article/details/80849962