How can I See the content of a MultipartForm request?

寵の児 提交于 2019-12-09 14:43:22

问题


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?


回答1:


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 both smaller than 2Gb, the maximum size of a byte array in Java, and small enough to be read into memory.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/4720077/how-can-i-see-the-content-of-a-multipartform-request

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