RestTemplate 发送请求

参考:https://www.cnblogs.com/kaibindirver/p/15398815.html

Restemconfig
 1 package com.config;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.boot.web.client.RestTemplateBuilder;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 import org.springframework.web.client.RestTemplate;
 8 
 9 /**
10  * @author: Amim
11  * @year: 2022/9
12  **/
13 @Configuration
14 public class Restemconfig {
15     @Autowired
16     private RestTemplateBuilder builder;
17 
18     @Bean
19     public RestTemplate restTemplate(){
20         return builder.build();
21     }
22 }
RequestUrlController
 1 package com.controle;
 2 
 3 import com.server.RequestUrlServer;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.web.bind.annotation.GetMapping;
 6 import org.springframework.web.bind.annotation.RestController;
 7 
 8 /**
 9  * @author: Amim
10  * @year: 2022/9
11  **/
12 
13 @RestController
14 public class RequestUrlController {
15 
16     @Autowired
17     private RequestUrlServer requesturlServer;
18 
19     @GetMapping("/aa")
20     public String requestB(){
21         return requesturlServer.resQuest();
22     }
23 
24 }
RequestUrlServer
 1 package com.server;
 2 
 3 import com.enter.User;
 4 import lombok.extern.slf4j.Slf4j;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.http.HttpHeaders;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.stereotype.Service;
 9 import org.springframework.web.client.RestTemplate;
10 
11 /**
12  * @author: Amim
13  * @year: 2022/9
14  **/
15 @Service
16 @Slf4j
17 public class RequestUrlServer {
18     private final String url = "https://account.cnblogs.com/user/userinfo";
19     @Autowired
20     private RestTemplate restTemplate;
21 
22     public String resQuest() {
23         ResponseEntity responseEntity = restTemplate.getForEntity(url,String.class );
24 ////      获取响应体
25         String body = String.valueOf(responseEntity.getBody());
26         return body;
27     }
28 }
User
 1 package com.enter;
 2 
 3 import lombok.Data;
 4 import org.apache.tomcat.util.buf.StringCache;
 5 
 6 /**
 7  * @author: Amim
 8  * @year: 2022/9
 9  **/
10 @Data
11 public class User {
12     String name;
13 }

 

posted @ 2022-10-14 13:01  amim  阅读(30)  评论(0编辑  收藏  举报