Ajax的text/plain、application/x-www-form-urlencoded和application/json

來源:互聯網
上載者:User

標籤:input   tip   app   private   accept   client   webkit   rac   urlencode   

HTTP請求中,如果是get請求,那麼表單參數以name=value&name1=value1的形式附到url的後面,如果是post請求,那麼表單參數是在請求體中,也是以name=value&name1=value1的形式在請求體中。通過chrome的開發人員工具可以看到如下(這裡是可讀的形式,不是真正的HTTP請求協議的請求格式):

get請求:

RequestURL:http://127.0.0.1:8080/test/test.do?name=mikan&address=street  Request Method:GET  Status Code:200 OK     Request Headers  Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8  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  Cookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8D  Host: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     Query String Parameters  name:mikan  address:street     Response Headers  Content-Length:2  Date:Sun, 11 May 2014 10:42:38 GMT  Server:Apache-Coyote/1.1

Post請求:

RequestURL:http://127.0.0.1:8080/test/test.do  Request Method:POST  Status Code:200 OK  Request Headers  Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8  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  Cache-Control:max-age=0  Connection:keep-alive  Content-Length:25  Content-Type:application/x-www-form-urlencoded  Cookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8D  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  Form Data  name:mikan  address:street  Response Headers  Content-Length:2  Date:Sun, 11 May 2014 11:05:33 GMT  Server:Apache-Coyote/1.1

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

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

而如果使用原生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的開發人員工具看到要求標頭如下:

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

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");

另外,如果使用jQuery,我使用1.11.0這個版本來測試,$.ajax post請求是不需要明確設定這個要求標頭的,其他版本的本人沒有親自測試過。相信在1.11.0之後的版本也是不需要設定的。不過之前有的就不一定了。這個沒有測試過。

 

後記:

最近在看書時才真正搞明白,伺服器為什麼會對錶單提交和檔案上傳做特殊處理,因為表單提交資料是名值對的方式,且Content-Type為application/x-www-form-urlencoded,而檔案上傳伺服器需要特殊處理,普通的post請求(Content-Type不是application/x-www-form-urlencoded)資料格式不固定,不一定是名值對的方式,所以伺服器無法知道具體的處理方式,所以只能通過擷取未經處理資料流的方式來進行解析。

jquery在執行post請求時,會設定Content-Type為application/x-www-form-urlencoded,所以伺服器能夠正確解析,而使用原生ajax請求時,如果不顯示的設定Content-Type,那麼預設是text/plain,這時伺服器就不知道怎麼解析資料了,所以才只能通過擷取未經處理資料流的方式來進行解析請求資料。

當後台使用@RequestBody以對象的形式來接收資料時,在前台必須以application/json的形式進行傳遞,同時使用JSON.stringify(data)將json對象轉換為json字串。

當你使用application/x-www-form-urlencoded格式來傳遞資料時,tomcat會將其組裝進一個Map中,後台只能用request.getParameter來訪問。

 

原生Ajax預設格式:text/plain

Jquery Ajax預設格式(Map) + Form表單POST提交格式:application/x-www-form-urlencoded

字元流 Ajax格式(Map):application/json  ( 同時使用JSON.stringify(data)將json對象轉換為json字串 )

檔案上傳:multipart/form-data

Ajax的text/plain、application/x-www-form-urlencoded和application/json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.