我想根据用户的特定请求从我的后端调用另一个web-api。例如,我想调用 Google FCM 发送消息api,以便在事件中向特定用户发送消息。
改造有任何方法可以实现这一目标吗?如果没有,我怎么能这样做?
答案 0 :(得分:58)
This website has some nice examples for using spring's 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);
}
答案 1 :(得分:8)
使用WebClient
而不是RestTemplate
的现代Spring 5+答案。
为特定的Web服务或资源将WebClient
配置为Bean(可以配置其他属性)。
@Bean
public WebClient localApiClient() {
return WebClient.create("http://localhost:8080/api/v3");
}
从您的服务中注入并使用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);
}
}
答案 2 :(得分:3)
正如这里的各种答案中提到的,WebClient 现在是推荐的路由。 您可以从配置 WebClient 构建器开始:
@Bean
public WebClient.Builder getWebClientBuilder(){
return WebClient.builder();
}
然后注入 bean,您可以使用 API 如下:
@Autowired
private WebClient.Builder webClientBuilder;
Product product = webClientBuilder.build()
.get()
.uri("http://localhost:8080/api/products")
.retrieve()
.bodyToMono(Product.class)
.block();
答案 3 :(得分:2)
为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);
}
}
使用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();
}
请参阅本教程[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm
答案 4 :(得分:2)
翻新有什么方法可以实现?如果没有,我该怎么办?
是
Retrofit是适用于Android和Java的类型安全的REST客户端。 Retrofit将您的HTTP API转变为Java接口。
有关更多信息,请参见以下链接
https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial
答案 5 :(得分:0)
您正尝试通过调用另一个API / URI来获取自定义POJO对象详细信息而不是String ,请尝试此解决方案。希望对于使用 RestTemplate 的人来说也很清楚,并且会有所帮助,
在 Spring Boot 中,首先我们需要在 @Configuration 带注释的类下为 RestTemplate 创建Bean。您甚至可以编写一个单独的类,并使用@Configuration进行注释,如下所示。
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
然后,无论您尝试使用RestTemplate的位置如何,都必须在服务/控制器下使用 @Autowired 或 @Injected 定义 RestTemplate 。 。使用以下代码,
@Autowired
private RestTemplate restTemplate;
现在,将看到如何使用上面创建的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();
快乐编码:)
答案 6 :(得分:-1)
在这种情况下需要下载我的 API,文件托管在其他服务器上。
在我的情况下,不需要使用 HTTP 客户端来下载外部 URL 中的文件,我结合了在以前的代码中为本地服务器中的文件工作的几个答案和方法。
我的代码是:
@GetMapping(value = "/download/file/pdf/", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<Resource> downloadFilePdf() throws IOException {
String url = "http://www.orimi.com/pdf-test.pdf";
RestTemplate restTemplate = new RestTemplate();
byte[] byteContent = restTemplate.getForObject(url, String.class).getBytes(StandardCharsets.ISO_8859_1);
InputStream resourceInputStream = new ByteArrayInputStream(byteContent);
return ResponseEntity.ok()
.header("Content-disposition", "attachment; filename=" + "pdf-with-my-API_pdf-test.pdf")
.contentType(MediaType.parseMediaType("application/pdf;"))
.contentLength(byteContent.length)
.body(new InputStreamResource(resourceInputStream));
}
它适用于 HTTP 和 HTTPS 网址!