问题描述
我使用的答案here要尽量让与数据上传POST
的要求,但我已经从服务器端的不同寻常的要求。该服务器是一个PHP脚本,它需要一个文件名
在内容处置
行,因为它是期待一个文件上传
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
我不能添加所需的文件名
字段内容 - 处置
行。因此,我试图用 FormBodyPart
,但只是把文件名
在单独一行。
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);
我怎样才能得到一个文件名
到内容处置
行,不先写我的字符串
成一个文件,然后回读出来呢?
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的自定义内容处置行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!