在 Servlet 中解析传入的多部分/表单数据参数的便捷方法
2022-08-31 15:00:55
是否有任何方便的方法来读取和解析传入请求中的数据。
例如,客户端启动发布请求
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
解析传入请求的最佳方法是什么?我不想写自己的解析器,可能有一个现成的解决方案。