第一种方法,获取post请求发送的Json数据
public static String JsonReq(HttpServletRequest request) {
BufferedReader br;
StringBuilder sb = null;
String reqBody = null;
try {
br = new BufferedReader(new InputStreamReader(
request.getInputStream()));
String line = null;
sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
reqBody = reqBody.substring(reqBody.indexOf("{"));
request.setAttribute("inputParam", reqBody);
System.out.println("JsonReq reqBody>>>>>" + reqBody);
return reqBody;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "jsonerror";
}
}
第二种方法,获取post、get请求发送的数据
public static String getParamString(HttpServletRequest request) {
Map<String, String[]> map = request.getParameterMap();
StringBuilder sb = new StringBuilder();
String reqBody = null;
try {
for (Entry<String, String[]> e : map.entrySet()) {
sb.append(e.getKey()).append("=");
String[] value = e.getValue();
if (value != null && value.length == 1) {
sb.append(value[0]).append("&");
} else {
sb.append(Arrays.toString(value)).append("\n");
}
}
reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
if (reqBody.contains("{") && reqBody.contains("}")) {
reqBody = reqBody.substring(reqBody.indexOf("{"));
reqBody = reqBody.substring(0, reqBody.lastIndexOf("}") + 1);
} else if (reqBody.contains("&")) {
reqBody = reqBody.substring(0, reqBody.lastIndexOf("&"));
}
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
System.out.println("JsonReq reqBody>>>>>" + reqBody);
}
return reqBody;
}