HTTP请求中的form data和request payload的区别

    xiaoxiao2021-03-25  64

    HTTP请求中的form data和request payload的区别: jQuery的ajax方法和post方法分别发送请求,在后台Servlet进行处理时结果是不一样的,比如用$.ajax方法发送请求时(data参数是一个JSON.stringify()处理后的字符串,而不是一个JSON对象) java后台接收方式不一样, (form data)可以用request.getParameter(接收参数名) (request payload)用request.getParameter是接收不到值,必须用输入流获取,得到字符串在转json request payload例子: 前端代码: //fetch的实现 var page=0; function data(){ page++;     // formData.append("page", page);     // formData.append("currentPageNo", 1); fetch('/getNineGoods_wap.shtml',{    method:"post",   headers: {        'Accept': 'application/json',        'Content-Type': 'application/json'       },       body:JSON.stringify({page:page}), }) .then((res) => {            return res.json();        })        .then( (datas) => {            console.log("新增角色--返回",datas);            if(datas.status === "200"){               console.log(datas.nineGoodsList)            }        })        .catch( (e) => {            console.log(e);        }) } $('.cd').on('click',function(){ data(); }) 后台代码: //得到一个json字符串(如:{"page":2}) String payloadRequest = getBody(request); //转为json对象 JSONObject jsonObject = JSONObject.fromObject(payloadRequest); String page = jsonObject.getString("page"); //获取http请求中的request payload public static String getBody(HttpServletRequest request) throws IOException {    String body = null;    StringBuilder stringBuilder = new StringBuilder();    BufferedReader bufferedReader = null;    try {        InputStream inputStream = request.getInputStream();        if (inputStream != null) {            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));            char[] charBuffer = new char[128];            int bytesRead = -1;            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {                stringBuilder.append(charBuffer, 0, bytesRead);            }        } else {            stringBuilder.append("");        }    } catch (IOException ex) {        throw ex;    } finally {        if (bufferedReader != null) {            try {                bufferedReader.close();            } catch (IOException ex) {                throw ex;            }        }    }    body = stringBuilder.toString();    return body; }
    转载请注明原文地址: https://ju.6miu.com/read-39708.html

    最新回复(0)