有没有方便的方法可以从传入的请求中读取和解析数据。
例如,客户端发起POST请求。
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!
// Send normal param.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"param\"");
writer.println("Content-Type: text/plain; charset=" + charset);
writer.println();
writer.println(param);
我无法使用request.getParameter("paramName")
获取参数。以下是代码:
BufferedReader reader = new BufferedReader(new InputStreamReader(
request.getInputStream()));
StringBuilder sb = new StringBuilder();
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
然而,对我来说显示了内容
-----------------------------29772313742745
Content-Disposition: form-data; name="name"
J.Doe
-----------------------------29772313742745
Content-Disposition: form-data; name="email"
abuse@spamcop.com
-----------------------------29772313742745
什么是解析传入请求的最佳方法?我不想编写自己的解析器,可能有现成的解决方案。
getParts()
总是返回零项。为什么在 Java 和 Servlet 3.0 中检索多部分表单如此困难?简直不敢相信! - basZero