1. 程式人生 > >HTTP請求中的form data和request payload的區別(request 後臺無法獲取參數)

HTTP請求中的form data和request payload的區別(request 後臺無法獲取參數)

origin logger res 部分 padding ble 處理 代碼 恰恰

轉載自:btg.yoyo

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

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

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

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

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

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

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

在servlet中,可以通過request.getParameter(name)的形式來獲取表單參數。

而如果使用原生AJAX POST請求的話:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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的開發者工具看到請求頭如下

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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中。

那麽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請求)的處理代碼如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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)是獲取不到的。

那麽這樣提交的參數我們該怎麽獲取呢?

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

1 2 3 4 5 6 7 8 9 10 11 12 13 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");

HTTP請求中的form data和request payload的區別(request 後臺無法獲取參數)