开发者

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?


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.


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.


Do you not know the content? Although, you are building the StringBody by supplying sharedValue. So, how could it be different than sharedValue.


I have printed the Multipart request by following code, You can try like

ByteArrayOutputStream bytes = new ByteArrayOutputStream();

entity.writeTo(bytes);

String content = bytes.toString();

Log.e("MultiPartEntityRequest:",content);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜