Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I See the content of a MultipartForm request?

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?

like image 733
asdasd Avatar asked Jan 18 '11 02:01

asdasd


People also ask

What is multipart form data content?

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.

How is multipart form data encoded?

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.

How do multipart requests work?

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


2 Answers

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.

like image 103
Onkar Parmar Avatar answered Oct 11 '22 12:10

Onkar Parmar


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.

like image 27
Lachlan Dowding Avatar answered Oct 11 '22 13:10

Lachlan Dowding