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

笑着哭i 提交于 2019-12-07 06:15:29

问题


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?


回答1:


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



回答2:


As a cleaner alternative to creating an extra anonymous inner class and adding side effects to protected methods, use 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();


来源:https://stackoverflow.com/questions/20672604/how-can-i-get-a-custom-content-disposition-line-using-apache-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!