如何使用Apache httpclient获取自定义Content-Disposition行?

mer*_*011 5 java apache apache-httpclient-4.x

我在这里使用答案尝试POST通过数据上传发出请求,但我从服务器端有不寻常的要求.该服务器是一个PHP脚本,需要filenameContent-Disposition行,因为它是期待一个文件上传.

Content-Disposition: form-data; name="file"; filename="-"
Run Code Online (Sandbox Code Playgroud)

但是,在客户端,我想发布一个内存缓冲区(在这种情况下是一个String)而不是一个文件,但让服务器处理它就好像它是一个文件上传.

但是,使用StringBody我无法在行filename上添加必填字段Content-Disposition.因此,我试图使用FormBodyPart,但这只是filename在一个单独的行.

HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
ContentBody body = new StringBody(data,                              
         org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM);
FormBodyPart fbp = new FormBodyPart("file", body); 
fbp.addField("filename", "-");                     
entity.addPart(fbp);                               
httppost.setEntity(entity);            
Run Code Online (Sandbox Code Playgroud)

如果没有先将我写入文件然后再将其读回来,我怎样才能filename进入该Content-DispositionString

ok2*_*k2c 5

尝试这个

StringBody stuff = new StringBody("stuff");
FormBodyPart customBodyPart = new FormBodyPart("file", stuff) {

    @Override
    protected void generateContentDisp(final ContentBody body) {
        StringBuilder buffer = new StringBuilder();
        buffer.append("form-data; name=\"");
        buffer.append(getName());
        buffer.append("\"");
        buffer.append("; filename=\"-\"");
        addField(MIME.CONTENT_DISPOSITION, buffer.toString());
    }

};
MultipartEntity entity = new MultipartEntity();
entity.addPart(customBodyPart);
Run Code Online (Sandbox Code Playgroud)