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

7

我正在使用这里的答案,尝试使用数据上传方式进行POST请求,但是服务器端有不同寻常的要求。服务器端是一个PHP脚本,需要在Content-Disposition行上指定一个filename,因为它需要上传文件。

Content-Disposition: form-data; name="file"; filename="-"

然而,在客户端上,我希望提交一个内存缓冲区(在这种情况下是一个字符串),而不是一个文件,但是让服务器将其处理为文件上传。

然而,使用StringBody时,我无法在Content-Disposition行上添加所需的filename字段。因此,我尝试使用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);            

如果我不想先把字符串写入文件再读出来,如何将filename放入Content-Disposition行中?

2个回答

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);

1
MultipartEntity 已被弃用。 - Lei Yang

2

作为一种更清洁的替代方案,避免创建额外的匿名内部类并向受保护方法添加副作用,可以使用FormBodyPartBuilder

StringBody stuff = new StringBody("stuff");

StringBuilder buffer = new StringBuilder();
    buffer.append("form-data; name=\"");
    buffer.append(getName());
    buffer.append("\"");
    buffer.append("; filename=\"-\"");
String contentDisposition = buffer.toString();

FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("file", stuff);
partBuilder.setField(MIME.CONTENT_DISPOSITION, contentDisposition);

FormBodyPart fbp = partBuilder.build();

如何使用上述代码与 MultipartEntityBuilder - Lei Yang
@LeiYang 我不确定,但你可以尝试使用上面的代码构建一个FormBodyPart,然后使用addPart()将其添加到MultipartEntityBuilder中。 - David Moles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接