apache HttpClient,通过表单上传文件:使用StringBody而不是FileBody
  Web服务器希望通过HTML表单上传文件。 
这就是我构建MultipartEntity的方式,它已经起作用了:
FileBody filePart = new FileBody(new File("emptyFile.txt"), "text/plain");
FormBodyPart fbp = new FormBodyPart("UploadService", filePart);
MultipartEntity mpe = new MultipartEntity();  
mpe.addPart(fbp);
事实是,我有我的数据在内存中,所以我不喜欢把它保存到磁盘的想法,所以我试图替换
FileBody filePart = new FileBody(new File("emptyFile.txt"), "text/plain");
同
StringBody filePart = new StringBody("");    
但第二种方式不起作用,服务器返回HTTP 500异常; 在线上记录数据,我注意到唯一的区别如下:
使用FileBody时的HTTP POST跟踪:
...
Content-Disposition: form-data; name="UploadService"; filename="emptyFile.txt"
...
使用StringBody时的HTTP POST跟踪:
...
Content-Disposition: form-data; name="UploadService"
...
也就是说,在FileBody上传中,它被指定了一个没有在StringBody上传中指定的“文件名”。 我怎样才能解决这个问题?
  使用StringBody你将无法设置文件名。  但是,您可以扩展StringBody并覆盖getFilename()以不返回null 。 
  根据FormBodyPart的来源,这应该足以具有所需的filename-parm参数: 
 protected void generateContentDisp(final ContentBody body) {
     StringBuilder buffer = new StringBuilder();
     buffer.append("form-data; name="");
     buffer.append(getName());
     buffer.append(""");
     if (body.getFilename() != null) {
         buffer.append("; filename="");
         buffer.append(body.getFilename());
         buffer.append(""");
     }
     addField(MIME.CONTENT_DISPOSITION, buffer.toString());
 }
只是放弃这一点,因为我有这个问题,并继续在我的搜索到这里...类似于上面的方法,但我想它更简单。
public class StringFileBody extends FileBody {
    private String data;
    public StringFileBody( String input, ContentType contentType ) {
        super( new File( "." ), contentType );
        data = input;
    }
    public StringFileBody( String input, ContentType contentType, String fileName ) {
        super( new File( "." ), contentType, fileName );
        data = input;
    }
    @Override
    public void writeTo( OutputStream out ) throws IOException {
        out.write( data.getBytes( ) );
    }
    @Override
    public long getContentLength( ) {
        return data.getBytes( ).length;
    }
}
上一篇: apache HttpClient, upload a file via form: use StringBody instead of FileBody
下一篇: nginx upload client
