当前位置: 首页 > 工具软件 > java-requests > 使用案例 >

java获取request里面的json

朱丰
2023-12-01

加上工具类的代码:
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {

        int readlen = request.getInputStream().read(buffer, i,
                contentLength - i);
        if (readlen == -1) {
            break;
        }
        i += readlen;
    }
    return buffer;
}


public static String getRequestPostStr(HttpServletRequest request)
        throws IOException {
    byte buffer[] = getRequestPostBytes(request);
    String charEncoding = request.getCharacterEncoding();
    if (charEncoding == null) {
        charEncoding = "UTF-8";
    }
    return new String(buffer, charEncoding);
}

 public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
        // POST
        } else {
            return getRequestPostStr(request);
        }
    }

三个方法。

在controller里面用
String json = getRequestJsonString(request);
System.out.println(json);
获取json数据把string变成json数据
JSONObject json_test = JSONObject.fromObject(json);
System.out.println(json_test.get(“producerid”));

 类似资料: