You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程方式调用GET API?Spring Boot微服务场景实操

嘿,我来给你分享几种在代码里调用这个视频流API的实用方法,都是项目里常用的:

方法一:使用Spring WebClient(推荐)

WebClient是Spring 5+推出的非阻塞式HTTP客户端,特别适合处理这种流式返回的场景,效率比传统的RestTemplate更高。

首先确保你的项目里引入了spring-boot-starter-webflux依赖,然后可以这样写调用代码:

import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import reactor.core.publisher.Flux;

// 注入Spring Boot自动配置的WebClient.Builder
@Autowired
private WebClient.Builder webClientBuilder;

public void fetchAndSaveVideo(String videoId) throws IOException {
    // 替换成服务A的实际地址和端口
    String apiUrl = "http://service-a-host:port/videos/" + videoId;

    webClientBuilder.build()
            .get()
            .uri(apiUrl)
            .retrieve()
            // 处理错误状态码,比如404视频不存在、500服务异常
            .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                    response -> response.bodyToMono(String.class)
                            .map(errorMsg -> new RuntimeException("调用视频API失败: " + errorMsg)))
            // 将响应转换为数据流
            .bodyToFlux(DataBuffer.class)
            .subscribe(dataBuffer -> {
                // 这里可以把流写入文件、转发到前端,或者做其他业务处理
                try (OutputStream outputStream = new FileOutputStream("downloaded_" + videoId + ".mp4")) {
                    outputStream.write(dataBuffer.asByteBuffer().array());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // 一定要释放DataBuffer资源,避免内存泄漏
                    DataBufferUtils.release(dataBuffer);
                }
            });
}
方法二:使用RestTemplate(传统同步方式)

如果你的项目还在使用RestTemplate,也可以轻松调用这个API,适合简单的同步场景:

import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.core.io.Resource;

@Autowired
private RestTemplate restTemplate;

public void downloadVideoSync(String videoId) throws IOException {
    String apiUrl = "http://service-a-host:port/videos/" + videoId;

    try {
        // 获取响应实体,Resource可以方便地处理输入流
        ResponseEntity<Resource> response = restTemplate.getForEntity(apiUrl, Resource.class);
        
        // 读取流并保存到文件(示例逻辑,你可以根据需求调整)
        try (InputStream inputStream = response.getBody().getInputStream();
             OutputStream outputStream = new FileOutputStream("downloaded_" + videoId + ".mp4")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    } catch (Exception e) {
        // 处理异常,比如视频不存在、服务不可用等
        System.err.println("调用API出错: " + e.getMessage());
    }
}
方法三:原生HttpURLConnection(无框架依赖)

如果不想依赖Spring的HTTP客户端,用JDK原生的HttpURLConnection也能实现,适合轻量场景:

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public void downloadVideoWithNativeCode(String videoId) throws IOException {
    String apiUrl = "http://service-a-host:port/videos/" + videoId;
    URL url = new URL(apiUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
    // 设置请求方法为GET
    connection.setRequestMethod("GET");
    // 配置连接超时和读取超时
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(10000);

    try (InputStream inputStream = connection.getInputStream();
         OutputStream outputStream = new FileOutputStream("downloaded_" + videoId + ".mp4")) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    } finally {
        // 关闭连接释放资源
        connection.disconnect();
    }
}

小提示:不管用哪种方法,都要记得用try-with-resources语法自动关闭IO资源,同时根据实际业务处理API返回的错误状态码(比如404、500等)。

内容的提问来源于stack exchange,提问作者SkyBlue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:43