我需要创建一个JAX-RS 2.0客户端,它使用MULTIPART_FORM_DATA内容类型发布文件和一些参数。 (不需要服务,只需要客户端)我已经看到一些依赖于特定实现的示例,比如Jersey或RESTEasy,但我不想将我的代码绑定到任何...特别是Apache CXF(我正在使用WAS Liberty Profile)。关于如何做的任何想法?我是否必须坚持某些特定的课程?如果是这样,我怎么能使用Apache CXF 3.0(Liberty使用CXF for JAX-RS 2.0)
由于
答案 0 :(得分:1)
[我目前无法根据已经写好的答案发表评论]
如果有人从Anatoly的答案中搜索IMultipartBody的Maven依赖项:
<dependency>
<groupId>com.ibm.websphere.appserver.api</groupId>
<artifactId>com.ibm.websphere.appserver.api.jaxrs20</artifactId>
<version>1.0.39</version>
<scope>provided</scope>
</dependency>
感谢https://github.com/OpenLiberty/open-liberty/issues/11942#issuecomment-619996093中的andymc12
答案 1 :(得分:0)
您可以使用此示例如何使用 jax-rs 2.0功能来实现它:https://www.ibm.com/support/knowledgecenter/SSD28V_8.5.5/com.ibm.websphere.wlp.nd.doc/ae/twlp_jaxrs_multipart_formdata_from_html.html这几乎是工作示例(某些语句应该包含在try-catch
块中,但你会看到什么时候将它发布到IDE。
package com.example.jaxrs;
@POST
@Consumes("multipart/form-data")
@Produces("multipart/form-data")
public Response postFormData(IMultipartBody multipartBody) {
List <IAttachment> attachments = multipartBody.getAllAttachments();
String formElementValue = null;
InputStream stream = null;
for (Iterator<IAttachment> it = attachments.iterator(); it.hasNext();) {
IAttachment attachment = it.next();
if (attachment == null) {
continue;
}
DataHandler dataHandler = attachment.getDataHandler();
stream = dataHandler.getInputStream();
MultivaluedMap<String, String> map = attachment.getHeaders();
String fileName = null;
String formElementName = null;
String[] contentDisposition = map.getFirst("Content-Disposition").split(";");
for (String tempName : contentDisposition) {
String[] names = tempName.split("=");
formElementName = names[1].trim().replaceAll("\"", "");
if ((tempName.trim().startsWith("filename"))) {
fileName = formElementName;
}
}
if (fileName == null) {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
formElementValue = sb.toString();
System.out.println(formElementName + ":" + formElementValue);
} else {
//handle the file as you want
File tempFile = new File(fileName);
...
}
}
if (stream != null) {
stream.close();
}
return Response.ok("test").build();
}