多部分表单数据不调用Web服务API

时间:2014-03-31 09:57:02

标签: java rest jersey jax-rs multipartform-data

我正在尝试从iOS客户端发送多部分表单数据。数据是多部分数据,我很确定。

服务器基于JAX-RS(Jersery)。如果我使用以下代码

@POST
@Path("/customerdetail")
@Consumes({"multipart/form-data"})
public String postCustomerDetails(InputStream message){ 

StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader; try { bufferedReader = new BufferedReader(new         InputStreamReader(message, "UTF-8")); 
String line = bufferedReader.readLine(); 
while(line != null){ inputStringBuilder.append(line);
inputStringBuilder.append('\n'); 
line = bufferedReader.readLine(); }
System.out.println(inputStringBuilder.toString()); 

}

我将多部分表单数据作为输入流。但我不知道如何继续从输入字符串中提取数据,而不是实现无聊的字符串操作。

如果我使用以下代码

@POST
@Path("/customerdetail")
@Consumes({"multipart/form-data"})
public String postCustomerDetails(FormDataMultiPart  formParams) {

}  

根本没有调用postCustomerDetails方法。

有关如何解析多部分数据的任何输入都将非常有用。我使用正确的方法吗?泽西岛专家请。帮我。提前谢谢。

1 个答案:

答案 0 :(得分:1)

在您的第一种方法中,您没有在多部分请求中注释您想要的“部分”,因此您的InputStream message会返回所有原始的多部分请求正文。

您需要做的是指定包含文件上传的表单名称。

例如,如果您的客户端有<input type="file" name="myfile">

public String postCustomerDetails(@FormDataParam("myfile") InputStream message){...}

通过这种方式,message仅包含您上传文件的内容,因此您无需解析整个请求正文以进行挖掘。

也许您没有在客户端应用中使用html表单,但是手动构建了一些多部分请求,您仍然需要知道表单中的名称。

在您当前的方法中,只需打印出整个请求体,就可以这样:

Content-Type: multipart/form-data; boundary=Boundary_1_511262261_1369143433608

--Boundary_1_511262261_1369143433608
Content-Type: text/plain
Content-Disposition: form-data; name="hello"

hello
--Boundary_1_511262261_1369143433608
Content-Type: application/xml
Content-Disposition: form-data; name="xml"

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><jaxbBean><value>xml</value></jaxbBean>
--Boundary_1_511262261_1369143433608
Content-Type: application/json
Content-Disposition: form-data; name="json"

{"value":"json"}
--Boundary_1_511262261_1369143433608--

name="hello"就是你追求的目标。然后你可以得到这样的3个部分:

public String postCustomerDetails(
  @FormDataParam("hello") InputStream helloInput,  // the file input for "hello"
  @FormDataParam("hello") FormDataContentDisposition helloDetail, // optional, for getting file name and size, etc
  @FormDataParam("xml") InputStream xmlInput,
  @FormDataParam("xml") FormDataContentDisposition xmlDetail,
  @FormDataParam("json") InputStream jsonInput,
  @FormDataParam("json") FormDataContentDisposition jsonDetail
){...}

对于你使用FormDataMultiPart的第二种方法,我从不使用那种低级api,但我只是测试了它的确有效。我不知道为什么不会为你触发它。

祝你好运。

相关问题