Java从REST API消费Octet Stream:接收文件并写入内容的方法
从JAX-RS Response接收文件并写入本地的实现方案
好的,我来帮你解决这个问题——从javax.ws.rs.core.Response对象中提取文件内容并写入本地其实很直接,下面是具体的步骤和代码示例:
1. 核心思路
客户端需要先调用你的/file/get API获取到Response对象,然后从Response中读取输入流,再将流的内容写入本地文件。同时要注意资源的关闭,避免泄漏。
2. 完整客户端代码实现
import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class FileDownloadClient { public static void main(String[] args) { Client client = null; Response response = null; InputStream inputStream = null; OutputStream outputStream = null; try { // 初始化JAX-RS客户端并构建请求 client = ClientBuilder.newClient(); WebTarget target = client.target("http://your-server-address/api/file/get") .queryParam("filePath", "/path/to/your/server/file.log"); // 替换为实际的服务器文件路径 // 发送GET请求获取响应 response = target.request().get(); // 检查响应是否成功 if (response.getStatus() == Response.Status.OK.getStatusCode()) { // 从响应中获取输入流 inputStream = response.readEntity(InputStream.class); // 写入本地文件,可自定义文件名 outputStream = new FileOutputStream("local_saved_file.log"); // 用缓冲区读写提升效率 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } System.out.println("文件下载并写入本地成功!"); } else { System.err.println("文件下载失败,响应状态码:" + response.getStatus()); } } catch (Exception e) { e.printStackTrace(); } finally { // 务必关闭所有打开的资源,避免内存泄漏 try { if (outputStream != null) outputStream.close(); if (inputStream != null) inputStream.close(); if (response != null) response.close(); if (client != null) client.close(); } catch (Exception e) { e.printStackTrace(); } } } }
3. 关键细节补充
- 服务器端参数绑定修正:你提供的服务器端代码中
filePath参数没有标注@QueryParam或@PathParam,会导致参数无法正确接收,建议修改为:public Response getFile(@QueryParam("filePath") String filePath) { // 原逻辑代码 } - 动态获取文件名:如果想复用服务器返回的文件名,可以解析
Content-Disposition响应头:String contentDisposition = response.getHeaderString("Content-Disposition"); String fileName = contentDisposition.split("filename=")[1].replace("\"", ""); // 之后用fileName作为本地文件名称 - 异常优化:实际项目中可以针对文件不存在、权限不足等场景做更细致的异常捕获和提示,不要仅打印栈轨迹。
内容的提问来源于stack exchange,提问作者Jayakumar Thangavel
相关产品推荐
相关产品推荐

