この記事では、すべてのリクエストパラメーターがjsonに配置されている場合にリクエストパラメーターを取得する方法を簡単に紹介します(requset.getparparameterを取得できません)
リクエストの例:
解決策のアイデア:ストリームを使用して文字列を読み取り、変換してから、jsonオブジェクトに変換します
public static String getPostString(HttpServletRequest request) {
BufferedReader in = null;
String parameters = "";
try {
in = new BufferedReader(new InputStreamReader(
request.getInputStream(), "utf-8"));
String ln;
StringBuffer stringBuffer = new StringBuffer();
while ((ln = in.readLine()) != null) {
stringBuffer.append(ln);
stringBuffer.append("\r\n");
}
parameters = stringBuffer.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return parameters;
}
// 实际应用
String reqBody = getPostString(request);
if(reqBody != null && !reqBody.equals("")) {
String reqBodyinfo= URLDecoder.decode(reqBody, HTTP.UTF_8);
JSONObject jsonData = (JSONObject) JSONValue.parse(reqBodyinfo);
String data = jsonData.get("data")+"";
// 如果data还是个json的话,就需要再转一下
JSONObject json_data = (JSONObject) JSONValue.parse(data);
// 再取其中的信息
int gameID = Integer.parseInt(json_data.get("gameID")+"");
}