POST 请求接收JSON数据

版权声明:创作不易,转载请声明博客地址,谢谢! https://blog.csdn.net/Is_I_black/article/details/85091847

一般请求接口我们使用的是GET和POST请求方式,

GET请求没什么好说的,

POST请求可以form表单提交请求的,也有用JSON数据请求的,而json数据在springmvc中使用@RequestBody进行接收,

下面是用HttpServletRequest接收的办法:

@RequestMapping("/notify")
public void notify(HttpServletRequest request_, HttpServletResponse response
/*1. requestBody读取*/, @RequestBody String request) {
		
	try {
                //LOGGER.info("JSON DATA >> " + request);
			
                /*4.二进制读取的工具类,下文有
                String responseStrBuilder = GetRequestJsonUtils.getRequestJsonObject(request_);
                LOGGER.info("responseStrBuilder DATA >> " + responseStrBuilder);*/           

                //2,字符串读取
                /*BufferedReader br = request_.getReader();
                String str, wholeStr = "";
                while((str = br.readLine()) != null){
                    wholeStr += str;
                }
                LOGGER.info("wholeStr DATA >> " + wholeStr);*/
		    
                //3.二进制读取
                /*InputStream is= null;
                is = request_.getInputStream();
                String bodyInfo = IOUtils.toString(is, "utf-8");
                LOGGER.info("bodyInfo DATA >> " + bodyInfo);*/
			
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
			e.printStackTrace();
		}
	}

接下来测试一下

使用POSTMAN测试工具

放开上文的注释4请求该接口

2018-12-19 10:56:07,793 INFO (IndexController.java:59)- JSON DATA >> {"name":"value"}

2018-12-19 10:56:07,795 INFO (GetRequestJsonUtils.java:26)- 请求方式 >>POST

2018-12-19 10:56:07,795 INFO (IndexController.java:62)- responseStrBuilder DATA >>

将@RequestBody注释并且将注释4,1放开再请求接口

java.lang.IllegalStateException: getInputStream() has already been called for this request
	at org.apache.catalina.connector.Request.getReader(Request.java:1205)
	at org.apache.catalina.connector.RequestFacade.getReader(RequestFacade.java:504)
	at com.cms.controller.index.IndexController.notify(IndexController.java:64)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
	at or


2018-12-19 11:02:25,466 INFO (IndexController.java:62)- responseStrBuilder DATA >> {"name":"value"}

可以得出结论:

1.如果已经用@RequestBody接收JSON,那么调用其它方法接收时将获取不到数据。

2.如果request.getInputStream(); request.getReader();和request.getParameter(“key”);这三个函数中任何一个函数执行一次后(可正常读取JSON数据),之后再执行就无效了,并且抛出如上异常。

下面是一个支持POST请求接收JSON二进制读取的工具类


import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
 
import com.alibaba.fastjson.JSONObject;
 
public class GetRequestJsonUtils {
	
	public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
		String json = getRequestJsonString(request);
		return JSONObject.parseObject(json);
	}
	 /***
     * 获取 request 中 json 字符串的内容
     * 
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    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);
        }
    }
 
    /**      
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例:
     * </pre>
     * @param request
     * @return
     * @throws IOException      
     */
    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;
    }
 
    /**      
     * 描述:获取 post 请求内容
     * <pre>
     * 举例:
     * </pre>
     * @param request
     * @return
     * @throws IOException      
     */
    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);
    }
 
}

https://blog.csdn.net/mccand1234/article/details/78013697

https://blog.csdn.net/java0311/article/details/78028702

https://blog.csdn.net/alan_waker/article/details/79477370

 

猜你喜欢

转载自blog.csdn.net/Is_I_black/article/details/85091847