I am using Apache HTTPClient 4. I am doing very normal multipart stuff like this:
val entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("filename", new FileBody(new File(fileName), "application/zip").asInstanceOf[ContentBody])
entity.addPart("shared", new StringBody(sharedValue, "text/plain", Charset.forName("UTF-8")));
val post = new HttpPost(uploadUrl);
post.setEntity(entity);
I want to see the contents of the entity (or post, whatever) before I send it. However, that specific method is not implemented:
entity.getContent() // not defined for MultipartEntity
How can I see what I am posting?
A multipart/form-data request body contains a series of parts separated by a boundary delimiter, constructed using Carriage Return Line Feed (CRLF), "--", and also the value of the boundary parameters. The boundary delimiter must not appear inside any of the encapsulated parts.
The encoding process is performed before data is sent to the server as spaces are converted to (+) symbol and non-alphanumeric characters or special characters are converted to hexadecimal (0-9, A-F) values as the ASCII character set is the format for sending data on the Internet.
Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).
Following would help for sure:
ByteArrayOutputStream content = new ByteArrayOutputStream();
httpEntity.writeTo(content);
logger.info("Calling "+url+" with data: "+content.toString());
The above has a fix in comparison to the first answer, there is no need to pass any parameter to ByteArrayOutputStream constructor.
Use the org.apache.http.entity.mime.MultipartEntity
writeTo(java.io.OutputStream) method to write the content to an java.io.OutputStream
, and then convert that stream to a String
or byte[]
:
// import java.io.ByteArrayOutputStream;
// import org.apache.http.entity.mime.MultipartEntity;
// ...
// MultipartEntity entity = ...;
// ...
ByteArrayOutputStream out = new ByteArrayOutputStream(entity.getContentLength());
// write content to stream
entity.writeTo(out);
// either convert stream to string
String string = out.toString();
// or convert stream to bytes
byte[] bytes = out.toByteArray();
Note: this only works for multipart entities small enough to be read into memory, and smaller than 2Gb which is the maximum size of a byte array in Java.
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