SpringBoot-RestTemplate

女爷i 2022-05-21 03:42 277阅读 0赞
    • 摘要
    • 使用

      • GET请求

        • 1 获取对象
        • 2 获取数组
        • 3 GET请求带有参数
        • 4 请求文件
      • POST请求

        • 1 请求携带cookie
        • 2 模拟提交表单
        • 3 模拟提交json
        • 4 通过URL提交POST请求

摘要

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

使用

GET请求

1 获取对象

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

2 获取数组

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

3 GET请求带有参数

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

4 请求文件

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

POST请求

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

2 模拟提交表单

  1. String url = "";
  2. HttpHeaders headers = new HttpHeaders();
  3. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  4. MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
  5. form.add("username", "admin");
  6. form.add("password", "admin");
  7. HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);
  8. ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

3 模拟提交json

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

4 通过URL提交POST请求

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

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读