Java Apache HttpClient上传文件时出错 [英] Java Apache HttpClient error uploading files

查看:546
本文介绍了Java Apache HttpClient上传文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用HttpClient 4.3.1上传文件。我需要添加以形成多部分输入流(以控制上载进度。)而不是File对象。
这是我的代码:

I want to upload a file using HttpClient 4.3.1. I need to add to form multipart an inputstream (to control upload progress.) instead of a File object. This is my code:

        byte[] dump = ...;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(SENDLOG_URL);      

        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
        meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // THIS WORKS!!  meb.addBinaryBody("log", new File("C:\\temp.zip"), ContentType.APPLICATION_OCTET_STREAM,"log.zip");
        InputStream is=new FileInputStream("C:\\temp.zip")
        meb.addBinaryBody("log", is, ContentType.DEFAULT_BINARY, "log.zip");            
        httppost.setEntity(meb.build());
        HttpResponse resp=httpclient.execute(httppost);
        is.close();

使用方法MultipartEntityBuilder.addBinaryBody(Strin,File)它可以工作,但使用MultipartEntityBuilder.addBinaryBody(Strin) ,InputStream)它不起作用。

Using the method MultipartEntityBuilder.addBinaryBody(Strin,File) it works, but using MultipartEntityBuilder.addBinaryBody(Strin,InputStream) it doesn't work.

java客户端不会抛出任何错误,但这是远程服务器(Apache)的答案:

The java client doesn't throw any error, but this is the answer of remote server (Apache):


HTTP / 1.1 400错误请求 [日期:星期四,2013年11月28日09:46:08 GMT,服务器:Apache / 2.4.6(Unix)mod_fcgid / 2.3.7,Content-Length:226,
连接:close,Content-Type:text / html; charset = iso-8859-1]

HTTP/1.1 400 Bad Request [Date: Thu, 28 Nov 2013 09:46:08 GMT, Server: Apache/2.4.6 (Unix) mod_fcgid/2.3.7, Content-Length: 226, Connection: close, Content-Type: text/html; charset=iso-8859-1]

为什么新文件()和新FileInputStream()之间会出现这种奇怪的行为?

Why this strange behaviour between new File() and new FileInputStream()?

推荐答案

这一切都非常简单。在前一种情况下,可以在已知其所有部分的长度的情况下计算多部分实体内容的总长度。此类实体可以包含在由 Content-Length 标头分隔的请求中。在后一种情况下,不能确定总实体长度,并且利用块编码来发送请求。显然,一些协议合规性有限的服务器端脚本无法处理没有 Content-Length 标头的请求。

That is all very simple. In the former case the total length of the multipart entity content can be calculated given the length of all its parts is known. Such entity can be enclosed in a request delimited by a Content-Length header. In the latter case the total entity length cannot be determined and the request is transmitted with chunk coding. Apparently some server side scripts with limited protocol compliance cannot handle requests without a Content-Length header.

这篇关于Java Apache HttpClient上传文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆