How can I See the content of a MultipartForm reque

2019-04-04 18:32发布

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?

3条回答
姐就是有狂的资本
2楼-- · 2019-04-04 18:45

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.

查看更多
Fickle 薄情
3楼-- · 2019-04-04 18:46

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

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-04 18:49

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);
查看更多
登录 后发表回答