How to get custom Content-Disposition string using Apache httpclient?

I am using the answer here to try to make a request POSTwith data loading, but I have unusual requirements from the server side. The server is a PHP script for which it is required filenamein a line Content-Dispositionbecause it expects a file to load.

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

However, on the client side, I would like to place a buffer (in this case String) in the memory instead of a file, but the server processes it as if it were a file upload.

However, using StringBody, I cannot add the required field filenameto the string Content-Disposition. So I tried using FormBodyPart, but just put it filenameon 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 , ?

+4
2

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

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();
+1

All Articles