HTTP請求中的form data和request payload的區別

 jQuery的ajax方法和post方法分別發送請求,在後臺Servlet進行處理時結果是不同的,好比用$.ajax方法發送請求時(data參數是一個JSON.stringify()處理後的字符串,而不是一個JSON對象),servlet裏能夠這樣使用Gson來解析:javascript

new Jsonparser().parse(request.getReader())

但此時是不可用request.getParam(key) 來取值的。java

若是用$.post方法來發送請求(data參數是一個JSON對象,而不要再用JSON.stringify()處理爲字符串了),結果偏偏相反。ajax

在Chrome中調試發現,$.ajax發送的請求顯示在request payload下面,而使用$.post方法發送的請求顯示在form data下面。有什麼區別呢?chrome

關鍵就是設置Content-type這個Header爲application/x-www-form-urlencoded,實際上對於常規的HTML頁面上的form的Content-type默認就是這個值。apache

這裏要注意post請求的Content-Type爲application/x-www-form-urlencoded,參數是在請求體中,即上面請求中的Form Data。app

在servlet中,能夠經過request.getParameter(name)的形式來獲取表單參數。jsp

 而若是使用原生AJAX POST請求的話:工具

function getXMLHttpRequest() {  
          var xhr;  
          if(window.ActiveXObject) {  
                   xhr= new ActiveXObject("Microsoft.XMLHTTP");  
          }else if (window.XMLHttpRequest) {  
                   xhr= new XMLHttpRequest();  
          }else {  
                   xhr= null;  
          }  
          return xhr;  
}  
  
function save() {  
          var xhr = getXMLHttpRequest();  
          xhr.open("post","http://127.0.0.1:8080/test/test.do");  
          var data = "name=mikan&address=street...";  
          xhr.send(data);  
          xhr.onreadystatechange= function() {  
                   if(xhr.readyState == 4 && xhr.status == 200) {  
                            alert("returned:"+ xhr.responseText);  
                   }  
          };  
}  

  經過chrome的開發者工具看到請求頭以下post

RequestURL:http://127.0.0.1:8080/test/test.do  
Request Method:POST  
Status Code:200 OK  
   
Request Headers  
Accept:*/*  
Accept-Encoding:gzip,deflate,sdch  
Accept-Language:zh-CN,zh;q=0.8,en;q=0.6  
AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2  
Connection:keep-alive  
Content-Length:28  
Content-Type:text/plain;charset=UTF-8  
Cookie:JSESSIONID=C40C7823648E952E7C6F7D2E687A0A89  
Host:127.0.0.1:8080  
Origin:http://127.0.0.1:8080  
Referer:http://127.0.0.1:8080/test/index.jsp  
User-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36  
   
Request Payload  
name=mikan&address=street  
   
Response Headers  
Content-Length:2  
Date:Sun, 11 May 2014 11:49:23 GMT  
Server:Apache-Coyote/1.1  

  注意請求的Content-Type爲text/plain;charset=UTF-8,而請求表單參數在RequestPayload中。ui

那麼servlet中經過request.getParameter(name)倒是空。爲何呢?而這樣的參數又該怎麼樣獲取呢?

爲了搞明白這個問題,查了些資料,也看了Tomcat7.0.53關於請求參數處理的源碼,終於搞明白了是怎麼回事。

HTTP POST表單請求提交時,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST請求若是不指定請求頭RequestHeader,默認使用的Content-Type是text/plain;charset=UTF-8。

 因爲Tomcat對於Content-Type multipart/form-data(文件上傳)和application/x-www-form-urlencoded(POST請求)作了「特殊處理」。下面來看看相關的處理代碼。

Tomcat的HttpServletRequest類的實現類爲org.apache.catalina.connector.Request(其實是org.apache.coyote.Request),而它對處理請求參數的方法爲protected void parseParameters(),這個方法中對Content-Type multipart/form-data(文件上傳)和application/x-www-form-urlencoded(POST請求)的處理代碼以下:

protectedvoid parseParameters() {  
           //省略部分代碼......  
           parameters.handleQueryParameters();// 這裏是處理url中的參數  
           //省略部分代碼......  
           if ("multipart/form-data".equals(contentType)) { // 這裏是處理文件上傳請求  
                parseParts();  
                success = true;  
                return;  
           }  
   
           if(!("application/x-www-form-urlencoded".equals(contentType))) {// 這裏若是是非POST請求直接返回,再也不進行處理  
                success = true;  
                return;  
           }  
           //下面的代碼纔是處理POST請求參數  
           //省略部分代碼......  
           try {  
                if (readPostBody(formData, len)!= len) { // 讀取請求體數據  
                    return;  
                }  
           } catch (IOException e) {  
                // Client disconnect  
                if(context.getLogger().isDebugEnabled()) {  
                    context.getLogger().debug(  
                            sm.getString("coyoteRequest.parseParameters"),e);  
                }  
                return;  
           }  
           parameters.processParameters(formData, 0, len); // 處理POST請求參數,把它放到requestparameter map中(即request.getParameterMap獲取到的Map,request.getParameter(name)也是從這個Map中獲取的)  
           // 省略部分代碼......  
}  
   
   protected int readPostBody(byte body[], int len)  
       throws IOException {  
   
       int offset = 0;  
       do {  
           int inputLen = getStream().read(body, offset, len - offset);  
           if (inputLen <= 0) {  
                return offset;  
           }  
           offset += inputLen;  
       } while ((len - offset) > 0);  
       return len;  
    }  

  從上面代碼能夠看出,Content-Type不是application/x-www-form-urlencoded的POST請求是不會讀取請求體數據和進行相應的參數處理的,即不會解析表單數據來放到request parameter map中。因此經過request.getParameter(name)是獲取不到的。

 那麼這樣提交的參數咱們該怎麼獲取呢?

固然是使用最原始的方式,讀取輸入流來獲取了,以下所示:

privateString getRequestPayload(HttpServletRequest req) {  
          StringBuildersb = new StringBuilder();  
          try(BufferedReaderreader = req.getReader();) {  
                   char[]buff = new char[1024];  
                   intlen;  
                   while((len = reader.read(buff)) != -1) {  
                            sb.append(buff,0, len);  
                   }  
          }catch (IOException e) {  
                   e.printStackTrace();  
          }  
          returnsb.toString();  
}  

  

固然,設置了application/x-www-form-urlencoded的POST請求也能夠經過這種方式來獲取。

 因此,在使用原生AJAX POST請求時,須要明確設置Request Header,即:

 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  

相關文章
相關標籤/搜索