How to remove request header from HttpEntity while uploading file

谁都会走 提交于 2021-02-11 13:41:35

问题


I am trying to send some message to mft server via REST API, and I'm using MultipartHttpEntityBuilder to build the message but along with original message some unwanted header and additional data is also getting attached. I found similar issue MultipartEntityBuilder: Omit Content-Type and Content-Transfer, but it was helpful.

My Code snippet :

HttpPut putRequest = new HttpPut(MFTSERVER_REST_LINK);

MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);        
builder.addBinaryBody("something","<head><content>xyz</content></head>".getBytes(), ContentType.APPLICATION_XML,"fileName");
HttpEntity httpEntity = builder.build();
putRequest.setEntity(httpEntity) ;

httpClient.execute(putRequest);

Expected content to be written to file :

<head><content>xyz</content></head>

But, actually written to file :

--p13fxV0SO5Y6zSxYnGPJlfGPgX8snL
Content-Disposition: form-data; name="something"; filename="fileName"
Content-Type: application/xml; charset=ISO-8859-1

<head><content>xyz</content></head>
--p13fxV0SO5Y6zSxYnGPJlfGPgX8snL--

Can someone help me to solve this issue ?


回答1:


If you are going to write Byte data in your post body. Then, you should use ByteArrayEntity instead of MultipartEntityBuilder. Because, with doWriteTo method in AbstractMultipartForm. There is no way you can remove or skip unwanted header to be written to file.

 void doWriteTo(
        final OutputStream out,
        final boolean writeContent) throws IOException {

        final ByteArrayBuffer boundary = encode(this.charset, getBoundary());
        for (final FormBodyPart part: getBodyParts()) {
            writeBytes(TWO_DASHES, out);
            writeBytes(boundary, out);
            writeBytes(CR_LF, out);

            formatMultipartHeader(part, out);

            writeBytes(CR_LF, out);

            if (writeContent) {
                part.getBody().writeTo(out);
            }
            writeBytes(CR_LF, out);
        }
        writeBytes(TWO_DASHES, out);
        writeBytes(boundary, out);
        writeBytes(TWO_DASHES, out);
        writeBytes(CR_LF, out);
    }

You could see, the list of elements which ware getting written to outputstream are boundary, header, body and then boundary again in sequence. So, if you wanted to write some content with bytes. Then, you should use ByteArrayEntity.

byte[] b = "This is hello".getBytes("UTF-8");
putRequest.setEntity(new ByteArrayEntity(b));


来源:https://stackoverflow.com/questions/59170102/how-to-remove-request-header-from-httpentity-while-uploading-file

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