如何通过Java Http Post发送和接受文件?

时间:2014-08-15 03:31:41

标签: java http http-post

我只想通过网络发送文本文件和JPEG文件。幸运的是,我可以访问服务器代码和客户端代码。这是我的(谷歌应用引擎)代码。

private void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
    GcsFilename filename = new GcsFilename("my-bucket", "my-file");
    Builder fileOptionsBuilder = new GcsFileOptions.Builder();
    fileOptionsBuilder.mimeType("text/html");
    GcsFileOptions fileOptions = fileOptionsBuilder.build();
    GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, fileOptions);

    byte[] buffer = new byte[1024];
    InputStream reader = req.getInputStream();
    BufferedOutputStream outStream = new BufferedOutputStream(Channels.newOutputStream(outputChannel));
    while(true) {
        int bytesRead = reader.read(buffer);
        if (bytesRead == -1) {
            break; // have a break up with the loop.
        } else if (bytesRead < 1024) {
            byte[] temp = Arrays.copyOf(buffer, bytesRead);
            outStream.write(temp);
        } else {
            outStream.write(buffer);
        }
    }

    outStream.close();
    outputChannel.close();
}

如您所见,我使用原始InputStream来获取通过网络发送的所有数据。

在客户端,我发送文本文件,如下所示:(在Android中)

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://my-hosted-url/postit");
MultipartEntity entity = new entity.addPart("myImageFile", new FileBody(someLogFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpost);

这很好......有点儿。问题是,当我尝试查看发送的文件/数据时,它上面有一个标题,如下:

--NNqarc4FsG0G8hUzd82A6TCjgzKH Content-Disposition: form-data; name="myString" Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 8bit STRING_VALUE ---NNqarc4FsG0G8hUzd82A6TCjgzKH Content-Disposition: form-data; name="myImageFile"; filename="something.txt" Content-Type: application/octet-stream Content-Transfer-Encoding: binary

[Thu Aug 14 17:14:26 PDT 2014] then the real log starts here...

如何摆脱以某种方式粘在身体上的标题?

1 个答案:

答案 0 :(得分:1)

这里有一个multipart request.这是一个请求,其中正文由分隔符字符串分隔的各个部分组成。

在您的情况下,它更容易被视为:

--NNqarc4FsG0G8hUzd82A6TCjgzKH 
Content-Disposition: form-data; name="myString" 
Content-Type: text/plain; charset=US-ASCII 
Content-Transfer-Encoding: 8bit 

STRING_VALUE 
---NNqarc4FsG0G8hUzd82A6TCjgzKH 
Content-Disposition: form-data; name="myImageFile"; filename="something.txt" 
Content-Type: application/octet-stream 
Content-Transfer-Encoding: binary

[binary here]

它有两个部分,每个部分都有相应的标题和正文。我猜你对这些尸体很感兴趣。你需要提取它们。

您可以阅读HTTP规范和/或有关多部分请求的规范并编写自己的解析器,或者您可以使用一些内置的(我不知道GAE是否准备好Servlet 3.0)或者第三方方法。见这些