我正在寻找一种仅使用标准 api 通过 jax-rs 客户端上传文件(多部分表单数据)的方法。
我能找到的最接近的解决方案是这个https://www.adam-bien.com/roller/abien/entry/sending_an_inputstream_to_jax但这不会产生MultiPart请求。
我发现的只是具体客户端实现的具体解决方案,例如 RestEASY (https://mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/) 或 Jersey (https:/ /howtodoinjava.com/jersey/jersey-file-upload-example/)或完全跳过 JaxRs 并使用 HttpClient(FileUpload with JAX-RS),但由于实现提供者将来很可能会发生变化,我最好的选择是严格遵守标准 API。
有什么东西,也许是 JaxRs 2.1 或者至少是一个交叉实现的解决方案? 提供只需注册的 MessageBodyWriter 或功能的库也很好。
据我所知,JAX-RS 客户端不直接支持上传多部分表单数据。但是,通过在 JAX-RS StreamingOutput 中使用 Apache HTTP 客户端中的 MultipartEntityBuilder,只需几行代码就可以从 JAX-RS 客户端进行多部分表单数据上传:
import java.io.File;
import java.util.UUID;
import javax.ws.rs.client.*;
import javax.ws.rs.core.*;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
public class MultipartJaxRsClient {
public static void main(String[] args) {
// prepare MultipartEntityBuilder:
String boundary = "-----------" + UUID.randomUUID().toString().replace("-", "");
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setBoundary(boundary);
// add file(s):
String multipartFieldName = "file1";
File fileToUpload = new File("test.pdf");
ContentType contentType = ContentType.create("application/pdf");
entityBuilder.addBinaryBody(multipartFieldName, fileToUpload, contentType, fileToUpload.getName()).build();
// ... add more files ...
// wrap HttpEntity in StreamingOutput:
HttpEntity entity = entityBuilder.build();
StreamingOutput streamingOutput = out -> entity.writeTo(out);
// use StreamingOutput in JAX-RS post request:
WebTarget target = ClientBuilder.newClient().target("http://server/path/to/upload");
String multipartContentType = MediaType.MULTIPART_FORM_DATA + "; boundary=\"" + boundary + "\"";
Response response = target.request().post(Entity.entity(streamingOutput, multipartContentType));
System.out.println("HTTP Status: " + response.getStatus());
}
}
以上代码使用 Apache HTTP Client 4.5.13 和 Apache CXF 3.5.4 JAX-RS 客户端进行测试:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.5.4</version>
</dependency>
StreamingOutputstreamingOutput = out->entity.writeTo(out); 出了什么?它在 Eclipse 中显示为未定义。 @史蒂芬D.