httpServletRequest.getQueryString()返回null

由于项目中有在使用GET请求时,请求参数包含特殊字符发生截断,想着使用POST方法,但是是在测试请求时发现接口返回参数异常:

java.lang.IllegalArgumentException: Source string may not be null
        at org.apache.http.util.Args.notNull(Args.java:54)
        at org.apache.http.entity.StringEntity.<init>(StringEntity.java:65)

这是HTTP请求工具类抛出的异常,我去看了源码,找到了异常抛出的地方:

public StringEntity(final String string, final ContentType contentType) throws UnsupportedCharsetException {
    
    
        super();
        Args.notNull(string, "Source string");//String 是请求参数,异常就是这里抛出来的
        Charset charset = contentType != null ? contentType.getCharset() : null;
        if (charset == null) {
    
    
            charset = HTTP.DEF_CONTENT_CHARSET;
        }
        this.content = string.getBytes(charset);
        if (contentType != null) {
    
    
            setContentType(contentType.toString());
        }
    }

	...
	public static <T> T notNull(final T argument, final String name) {
    
    
        if (argument == null) {
    
    
            throw new IllegalArgumentException(name + " may not be null");
        }
        return argument;
    }

返回上层,查看接口发现:
参数的获取的是用的httpServletRequest.getQueryString()方法,由此我推断方法没有能获取到请求参数。

String params = request.getQueryString();

光是推测还是不行的,自己写个接口论证一下:

  @RequestMapping(value = "/test")
    public String testRequest(HttpServletRequest request, HttpResponse response) {
    
    
        log.info("request.getQueryString():{}",request.getQueryString());
        log.info("request.getParameterMap():{}", request.getParameterMap());
        return "success";
    }

看看打印结果,可以看到,使用GET方法是可以正常获取的,但是POST方法就是null
在这里插入图片描述
为此我去查了一下,文档上说方法返回的是URL中的查询字符,也就说GET方法拼接上去的参数。这也能解释为什么POST方法拿不到了,因为参数在请求体中。

getQueryString
java.lang.String getQueryString()
Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
Returns:
a String containing the query string or null if the URL contains no query string. The value is not decoded by the container.

stackoverflow上也有人遇到同样的问题,如果想在GET和POS都拿到参数,使用getParameter()方法。同时我发现还有个getParameterMap()方法,可以获取所以参数,返回在Map集合中,如上的测试图中,都获取到了参数。

The easiest way to get hold of request parameters is to use request.getParameter(). This works for both GET and POST requests.
POST requests typically carry their parameters within the request body, which is why the request.getQueryString() method returns null.

文档上如是说:
在这里插入图片描述
大概意思就是方法能获取到URL中包含的请求参数或者请求体中的表单信息,返回的Map以参数名为Key,Value是String 数组。

猜你喜欢

转载自blog.csdn.net/Logicr/article/details/111665749
今日推荐