通过JSON Post请求将文件上传到Teambox提供的Web服务

时间:2011-06-26 14:54:44

标签: java web-services json file-upload

请参阅(看起来非常简单的文档):https://teambox.com/api/upload

我想作为JSON传递的参数是:

{
  "page_id": 456,
  "project_id": 123,
  "name": "Name",
  "asset": "<File Data>"
}

到网址:/api/1/uploads

我的猜测是我要传递一个表单的编码请求来代替上面的文件数据。 但我一直收到错误:/ api / 1 / uploads返回的响应状态为422 null

所以这是我的代码:

表格

     <FORM  ENCTYPE="multipart/form-data" ACTION=
"up.jsp" METHOD=POST>
                <br><br><br>
          <center><table border="2" >
                    <tr><center><td colspan="2"><p align=
"center"><B>PROGRAM FOR UPLOADING THE FILE</B><center></td></tr>
                    <tr><td><b>Choose the file To Upload:</b>
</td>
                    <td><INPUT NAME="F1" TYPE="file"></td></tr>
                                        <tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
             <table>
     </center>      
     </FORM>

up.jsp

<%@ page import="java.io.*" %>
<%@ page import="com.sun.jersey.api.client.*" %>
<%@ page import="com.sun.jersey.api.client.filter.*" %>
<%@ page import="com.google.gson.*" %>
<%@ page import="OtherClasses.UploadFile" %>
<%  
         StringBuffer inputLine = new StringBuffer();
         try 
         {
            DataInputStream dis = new DataInputStream(new   DataInputStream(request.getInputStream()));
            String tmp; 
            while ((tmp = dis.readLine()) != null) {
                inputLine.append(tmp);
                //System.out.println(tmp);
            }
            dis.close();
        } 
        catch (IOException ioe) {
            System.out.println("IOException: " + ioe);
        }
        String encodedRequest = inputLine.toString();
        out.print(encodedRequest);

                Client client = Client.create(); 
        client.addFilter(new HTTPBasicAuthFilter("username", "password"));
        WebResource webResource = client.resource("http://my-server-ip:3000");

        UploadFile file = new UploadFile();
        file.setAsset(encodedRequest);
        file.setName("Afile");
        file.setPage_id("2");//404 error if page doesn't exist.
        file.setProject_id("1");

        ClientResponse r = webResource.path("/api/1/uploads").type("application/json").post(ClientResponse.class,new Gson().toJson(file));
        System.out.println(r);



%>

我一直得到响应错误代码为422.请提出建议。我该怎么办? 感谢

1 个答案:

答案 0 :(得分:0)

您需要做的是使用文件上传库(例如Commons File Upload)来提取实际文件内容(而不是整个请求主体),然后将文件base64编码为{{1} }字段。

顺便说一句,API文档非常糟糕:他们说asset和表单编码,但没有提供有意义的示例。我很确定你所做的事情(在整个HTTP请求中读取并保存为"<File Data>"字段)将无效。