如何在RestAssured中为PUT(非多部分)请求上传文件
使用RestAssured向PUT API上传文件的解决方案
你可以直接将文件的InputStream作为PUT请求的请求体发送,RestAssured的PUT请求完全支持设置body,不存在仅适用于POST的限制。以下是具体实现方式:
基础实现示例
直接通过given().body()传入文件InputStream完成上传,对应你提供的curl命令逻辑:
import io.restassured.RestAssured; import java.io.FileInputStream; import java.io.IOException; public class PutFileUploadTest { public static void main(String[] args) throws IOException { // 读取目标文件为InputStream try (FileInputStream fileInputStream = new FileInputStream("<替换为你的文件路径>")) { RestAssured.given() // 添加curl中对应的请求头 .header("Content-Type", "application/octet-stream") // 根据API实际要求调整 .header("X-Custom-Header", "header-value") // 示例自定义头,按需添加 // 将InputStream作为PUT请求体 .body(fileInputStream) .when() .put("http://localhost:1080/update") .then() .statusCode(200); // 验证响应状态码,按需修改 } } }
使用RequestSpecBuilder的实现
如果需要复用请求配置,也可以结合RequestSpecBuilder来实现:
import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; import java.io.FileInputStream; import java.io.IOException; public class PutFileUploadWithSpec { public static void main(String[] args) throws IOException { // 构建请求规范 RequestSpecification requestSpec = new RequestSpecBuilder() .setBaseUri("http://localhost:1080") .addHeader("Content-Type", "application/octet-stream") .addHeader("X-Custom-Header", "header-value") .build(); try (FileInputStream fileInputStream = new FileInputStream("<替换为你的文件路径>")) { RestAssured.given() .spec(requestSpec) .body(fileInputStream) .when() .put("/update") .then() .statusCode(200); } } }
关键说明
- curl的
--upload-file本质就是将文件内容作为PUT请求的请求体发送,上述代码完全匹配该逻辑。 - 务必根据API要求设置正确的
Content-Type:二进制文件用application/octet-stream,文本文件用text/plain,图片类用image/png等。 - 使用try-with-resources语法可以自动关闭InputStream,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Kulkarni Sachin
相关产品推荐
相关产品推荐

