Java Web,如何获取request中的请求参数呢?
- /***
- * Get request query string
- * @param request
- * @return byte[]
- */
- public byte[] getRequestStr(HttpServletRequest request){
- int contentLength = request.getContentLength();
- byte buffer[] = new byte[contentLength];
- for (int i = 0; i < contentLength;) {
- try {
- int readlen = request.getInputStream().read(buffer, i,
- contentLength - i);
- if (readlen == -1) {
- break;
- }
- i += readlen;
- } catch (IOException ioexception) {
- ioexception.printStackTrace();
- } finally {
- // logger.info("Json Request:" + requestPacket);
- }
- }
- return buffer;
- }
上述方法返回的是byte数组。
下面的方法直接返回字符串:
- /***
- * Get request query string
- *
- * @param request
- * @return
- * @throws UnsupportedEncodingException
- */
- public String getRequestStr(HttpServletRequest request) throws UnsupportedEncodingException{
- byte buffer[]=getRequestBytes(request);
- String charEncoding=request.getCharacterEncoding();
- if(charEncoding==null){
- charEncoding="UTF-8";
- }
- return new String(buffer,charEncoding);
- }
应用:上述方法一般用于在filter(javax.servlet.Filter)中获取请求参数,进行转发