Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a custom Content-Disposition line using Apache httpclient?

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?

like image 290
merlin2011 Avatar asked Dec 19 '13 02:12

merlin2011


1 Answers

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);
like image 179
ok2c Avatar answered Dec 08 '22 05:12

ok2c