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.
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?
Try this
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With