如何使用 Apache httpclient 获得自定义的 Content-Disposition 行? [英] How can I get a custom Content-Disposition line using Apache httpclient?
问题描述
我正在使用此处的答案来尝试制作POST
请求上传数据,但我对服务器端有不寻常的要求.服务器是一个 PHP 脚本,它需要 Content-Disposition
行上的 filename
,因为它需要上传文件.
I am using the answer here to try to make a POST
request with a data upload, but I have unusual requirements from the server-side. The server is a PHP script which requires a filename
on the Content-Disposition
line, because it is expecting a file upload.
Content-Disposition: form-data; name="file"; filename="-"
但是,在客户端,我想发布一个内存缓冲区(在本例中为字符串)而不是文件,但让服务器将其处理为文件上传.
However, on the client side, I would like to post an in-memory buffer (in this case a String) instead of a file, but have the server process it as though it were a file upload.
但是,使用 StringBody
我无法在 Content-Disposition
行上添加必需的 filename
字段.因此,我尝试使用 FormBodyPart
,但这只是将 filename
放在单独的行上.
However, using StringBody
I cannot add the required filename
field on the Content-Disposition
line. Thus, I tried to use FormBodyPart
, but that just put the filename
on a separate line.
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
行,而无需先将 String
写入文件然后再读回又出来了?
How can I get a filename
into the Content-Disposition
line, without first writing my String
into a file and then reading it back out again?
推荐答案
试试这个
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);
这篇关于如何使用 Apache httpclient 获得自定义的 Content-Disposition 行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!