在Spring-Boot中从我的服务器调用另一个rest api

Ken*_*nji 46 api spring-data retrofit spring-boot

我想根据用户的特定请求从我的后端调用另一个web-api.例如我想调用google FCM发送消息api,以便在事件上向特定用户发送消息.

改造有什么方法来实现这一目标?或者如果不是我怎么能这样做?

Tor*_* N. 78

这个网站有一些使用spring的RestTemplate的好例子. 下面是一个代码示例,说明如何获取一个简单的对象:

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}
Run Code Online (Sandbox Code Playgroud)

  • [RestTemplate](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html) 将在未来版本中弃用,请使用更现代的替代[WebClient](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html) (14认同)
  • [在下面为 WebClient 添加了答案](/sf/answers/4441167391/)。 (3认同)

and*_*ero 17

Modern Spring 5+ 答案使用WebClient代替RestTemplate.

WebClient将特定的 Web 服务或资源配置为 bean(可以配置其他属性)。

@Bean
public WebClient localApiClient() {
    return WebClient.create("http://localhost:8080/api/v3");
}
Run Code Online (Sandbox Code Playgroud)

从您的服务中注入并使用 bean。

@Service
public class UserService {

    private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);

    private final WebClient localApiClient;

    @Autowired
    public UserService(WebClient localApiClient) {
        this.localApiClient = localApiClient;
    }

    public User getUser(long id) {
        return localApiClient
                .get()
                .uri("/users/" + id)
                .retrieve()
                .bodyToMono(User.class)
                .block(REQUEST_TIMEOUT);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 对于那些正在搜索包含 WebClient 的软件包的人来说,它是“org.springframework.boot”中的“spring-boot-starter-webflux”。您必须将其包含在 pom.xml 文件中。 (5认同)

Nal*_*chu 7

尝试通过调用另一个API / URI而不是String来尝试获取自定义POJO对象详细信息作为输出,请尝试此解决方案。我希望它对于如何使用RestTemplate也将是清楚的,对您有所帮助,

Spring Boot中,首先我们需要在@Configuration带注释的类下为RestTemplate创建Bean 。您甚至可以编写一个单独的类,并使用@Configuration进行注释,如下所示。

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,你必须定义RestTemplate@Autowired@Injected服务/控制器,无论您在什么尝试使用RestTemplate下。使用以下代码,

@Autowired
private RestTemplate restTemplate;
Run Code Online (Sandbox Code Playgroud)

现在,将看到如何使用上面创建的RestTemplate从我的应用程序中调用另一个api的部分。为此,我们可以使用多种方法,例如execute()getForEntity()getForObject()等。在这里,我将代码放在execute()的示例中。我什至尝试了另外两个,我遇到了将返回的LinkedHashMap转换为预期的POJO对象的问题。下面的execute()方法解决了我的问题。

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();
Run Code Online (Sandbox Code Playgroud)

快乐编码:)


小智 5

为 Rest Template 创建 Bean 以自动连接 Rest Template 对象。

@SpringBootApplication
public class ChatAppApplication {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ChatAppApplication.class, args);
    }

}
Run Code Online (Sandbox Code Playgroud)

使用 RestTemplate - exchange() 方法使用 GET/POST API。下面是在控制器中定义的 post api。

@RequestMapping(value = "/postdata",method = RequestMethod.POST)
    public String PostData(){

       return "{\n" +
               "   \"value\":\"4\",\n" +
               "   \"name\":\"David\"\n" +
               "}";
    }

    @RequestMapping(value = "/post")
    public String getPostResponse(){
        HttpHeaders headers=new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity=new HttpEntity<String>(headers);
        return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
    }
Run Code Online (Sandbox Code Playgroud)

参考本教程[1]

[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm


小智 5

正如此处的各种答案中所提到的,WebClient 现在是推荐的路线。您可以从配置 WebClient 构建器开始:

@Bean
public WebClient.Builder getWebClientBuilder(){
    return WebClient.builder();
}
Run Code Online (Sandbox Code Playgroud)

然后注入 bean,您就可以使用 API,如下所示:

@Autowired
private WebClient.Builder webClientBuilder;


Product product = webClientBuilder.build()
            .get()
            .uri("http://localhost:8080/api/products")
            .retrieve()
            .bodyToMono(Product.class)
            .block();
Run Code Online (Sandbox Code Playgroud)