要调用第三方接口并获取文件流,可以使用以下步骤:
导入相关的依赖:添加RestTemplate 和 HttpComponentsClientHttpRequestFactory 依赖。<dependencies> <!-- RestTemplate --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- HttpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency></dependencies>创建 RestTemplate 实例,并配置 HttpComponentsClientHttpRequestFactory。@Configurationpublic class RestTemplateConfig { @Bean public RestTemplate restTemplate() { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(factory); }}在需要调用第三方接口的地方注入 RestTemplate。@Autowiredprivate RestTemplate restTemplate;使用 restTemplate 发送 HTTP 请求,并获取文件流。public InputStream getRemoteFile(String url) { ResponseEntity<Resource> response = restTemplate.getForEntity(url, Resource.class); Resource resource = response.getBody(); try { return resource.getInputStream(); } catch (IOException e) { e.printStackTrace(); } return null;}上述代码中,url 是第三方接口的 URL,将其作为参数传递给 getRemoteFile 方法。该方法使用 restTemplate.getForEntity 发送 GET 请求,并将响应的 Resource 对象中的文件流返回。
注意:这仅适用于返回文件流的接口,如果返回的是文件的字节数组或字符串等形式,可以根据实际情况进行调整。