java web獲取請求體內容


Java Web中如何獲取請求體內容呢?

我們知道請求方式分為兩種:Get,Post。

/*** 
     * Compatible with GET and POST 
     *  
     * @param request 
     * @return : <code>byte[]</code> 
     * @throws IOException 
     */  
    public static byte[] getRequestQuery(HttpServletRequest request)  
            throws IOException {  
        String submitMehtod = request.getMethod();  
        String queryString = null;  
  
        if (submitMehtod.equals("GET")) {// GET  
            queryString = request.getQueryString();  
            String charEncoding = request.getCharacterEncoding();// charset  
            if (charEncoding == null) {  
                charEncoding = "UTF-8";  
            }  
            return queryString.getBytes(charEncoding);  
        } else {// POST  
            return getRequestPostBytes(request);  
        }  
    }  
  
/*** 
     * Get request query string, form method : post 
     *  
     * @param request 
     * @return byte[] 
     * @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;  
    }  
/*** 
     * Get request query string, form method : post 
     *  
     * @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);  
    }  

說明:當請求方式為“Get”時,直接使用request.getQueryString()獲取String

當請求方式為“Post”時,讀取InputStream(request.getInputStream())


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM