从输入流解析多部分/表单数据的库和示例 [英] Library and examples of parsing multipart/form-data from inputstream
本文介绍了从输入流解析多部分/表单数据的库和示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对我发送的一种 HTTP 请求的响应是一个 multipart/form-data 看起来像:
The response to one kind of HTTP request I send is a multipart/form-data looks something like:
--------boundary123
Content-Disposition: form-data; name="json"
Content-Type: application/json
{"some":"json"}
--------boundary123
Content-Disposition: form-data; name="bin"
Content-Type: application/octet-stream
<file data>
--------boundary123
我一直在使用 apache 来发送和接收 HTTP 请求,但我似乎找不到一种简单的方法来使用它来解析上述内容以便轻松访问表单字段.
I've been using apache to send and receive the HTTP requests, but I can't seem to find an easy way to use it to parse the above for easy access of the form fields.
我不想重新发明轮子,所以我正在寻找一个可以让我做类似以下事情的库:
I would prefer not to reinvent the wheel, so I'm looking for a library that allows me to do something similar to:
MultipartEntity multipart = new MultipartEntity(inputStream);
InputStream bin = multipart.get("bin");
有什么建议吗?
推荐答案
使用弃用构造函数的示例代码:
Example code using deprecated constructor:
import java.io.ByteArrayInputStream;
import org.apache.commons.fileupload.MultipartStream;
public class MultipartTest {
// Lines should end with CRLF
public static final String MULTIPART_BODY =
"Content-Type: multipart/form-data; boundary=--AaB03x
"
+ "
"
+ "----AaB03x
"
+ "Content-Disposition: form-data; name="submit-name"
"
+ "
"
+ "Larry
"
+ "----AaB03x
"
+ "Content-Disposition: form-data; name="files"; filename="file1.txt"
"
+ "Content-Type: text/plain
"
+ "
"
+ "HELLO WORLD!
"
+ "----AaB03x--
";
public static void main(String[] args) throws Exception {
byte[] boundary = "--AaB03x".getBytes();
ByteArrayInputStream content = new ByteArrayInputStream(MULTIPART_BODY.getBytes());
@SuppressWarnings("deprecation")
MultipartStream multipartStream =
new MultipartStream(content, boundary);
boolean nextPart = multipartStream.skipPreamble();
while (nextPart) {
String header = multipartStream.readHeaders();
System.out.println("");
System.out.println("Headers:");
System.out.println(header);
System.out.println("Body:");
multipartStream.readBodyData(System.out);
System.out.println("");
nextPart = multipartStream.readBoundary();
}
}
}
这篇关于从输入流解析多部分/表单数据的库和示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文