Java HttpServletRequest获取JSON POST数据
我正在HTTP POST到URL http:// laptop:8080 / apollo / services / rpc?cmd = execute
与POST数据
{ "jsondata" : "data" }Http请求的Content-Type为 application/json; charset=UTF-8
如何从HttpServletRequest获取POST数据(jsondata)?
如果我枚举请求参数,则只能看到一个参数“ cmd”,而看不到POST数据。
回答:
通常,你可以以相同的方式在Servlet中获取GET和POST参数:
request.getParameter("cmd");但仅当POST数据被编码为内容类型的键/值对时:“ application / x-www-form-urlencoded”,例如使用标准HTML表单时。
如果你对发布数据使用不同的编码模式,例如在发布json数据流的情况下,则需要使用可以处理以下内容的原始解码器的自定义解码器:
BufferedReader reader = request.getReader();Json后处理示例(使用org.json包)
public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }
  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }
  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}
以上是 Java HttpServletRequest获取JSON POST数据 的全部内容, 来源链接: utcz.com/qa/436439.html








