java - 从 HttpServletRequest 获取 POST 内容
问题描述
我想从Java Servlet中的POST请求中读出数据。该 servlet 作为服务在 Geoserver 上运行并使用 URL 调用。
POST 请求(使用 python 脚本创建):
POST http://localhost:8080/geoserver/ows?request=upload&service=GeoTransfer&version=1.0.0 HTTP/1.1
Host: localhost:8080
User-Agent: python-requests/2.20.0
Accept-Encoding: gzip, deflate
Accept: application/xml
Connection: keep-alive
Authorization: admin:admin
fileName: transfer.xml
Content-Type: application/xml
Content-Length: 489
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<transfer>
<enviroment>Test</enviroment>
<product>Testproduct</product>
<user>admin</user>
</transfer>
Java 小服务程序:
public void upload(HttpServletRequest request, httpServletResponse response)
throws ServletException, IOException {
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
System.out.println("===== Begin Body =====");
if ("POST".equalsIgnoreCase(request.getMethod())) {
try {
Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
System.out.println(s.hasNext() ? s.next() : "");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("===== End Body =====\n");
}
输出:
===== Begin headers =====
Authorization = admin:admin
fileName = transfer.xml
Accept = application/xml
User-Agent = python-requests/2.20.0
Connection = keep-alive
Host = localhost:8080
Accept-Encoding = gzip, deflate
Content-Length = 489
Content-Type = application/xml
===== End headers =====
===== Begin Body =====
===== End Body =====
问题:
为什么我不能读出 xml 数据体?请求有问题并且数据没有传递给Java吗?
编辑1:
尝试使用 Inputstream 的其他方法,但正文始终是空行。如果他创建请求对象,可能是服务器忽略正文并仅使用标头的问题?
编辑2:
尝试 Majid Khakwani 回答并获得空字符串。我打印出来request.getContentLength()
,它是489
。该方法是从标头中获取此数字还是从对象请求中获取内容的实际长度?
解决方案
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String xml = null;
try {
byte[] xmlData = new byte[request.getContentLength()];
//Start reading XML Request as a Stream of Bytes
InputStream sis = request.getInputStream();
BufferedInputStream bis = new BufferedInputStream(sis);
bis.read(xmlData, 0, xmlData.length);
if (request.getCharacterEncoding() != null) {
xml = new String(xmlData, request.getCharacterEncoding());
} else {
xml = new String(xmlData);
}
//xml and xmlData contains incomplete data
} catch (IOException ioe) {
...
}
推荐阅读
- c# - 在 C# 中具有语义操作的类型安全 Backus-Naur-Form DSL
- microsoft-graph-api - 未为特定 O365 域创建 MS Graph 日历事件
- javascript - jQuery Raty 在使用浏览器的导航来回前进时重复星星
- python - 如何绘制从不同列着色的堆叠 seaborn 直方图
- javascript - 为什么输入 field.type 返回未定义?
- javascript - HTML href 作为 Google Apps 脚本变量
- python - 休眠直到在 python (linux) 中修改文件
- php - 使用PHP获取姓氏4个字母的姓名首字母
- notifications - OneM2M:从 IN-CSE 更改 MN-CSE 配置
- r - R中跨数据框的重叠