Ajax's Text/plain, application/x-www-form-urlencoded, and Application/json

Source: Internet
Author: User
Tags form post webp chrome developer

Ajax of Text/plain, application/x-www-form-urlencoded and Application/json

In the HTTP request, if it is a GET request, then the form parameter is appended to the URL in the form of name=value&name1=value1, and if it is a POST request, then the form parameter is in the request body, also in the name=value&name1= The form of value1 in the request body. The Chrome developer tool can be seen as follows (here is a readable form, not a request format for the real HTTP request protocol):

GET Request:

[plain] view plain copy

  1. Requesturl:http://127.0.0.1:8080/test/test.do?name=mikan&address=street
  2. Request Method:get
  3. Status code:200 OK
  4. Request Headers
  5. accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
  6. Accept-encoding:gzip,deflate,sdch
  7. accept-language:zh-cn,zh;q=0.8,en;q=0.6
  8. alexatoolbar-alx_ns_ph:alexatoolbar/alxg-3.2
  9. Connection:keep-alive
  10. cookie:jsessionid=74ac93f9f572980b6fc10474cd8edd8d
  11. host:127.0.0.1:8080
  12. referer:http://127.0.0.1:8080/test/index.jsp
  13. user-agent:mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.149 safari/537.36
  14. Query String Parameters
  15. Name:mikan
  16. Address:street
  17. Response Headers
  18. Content-length:2
  19. Date:sun, 10:42:38 GMT
  20. server:apache-coyote/1.1

POST request:

[plain] view plain copy

  1. Requesturl:http://127.0.0.1:8080/test/test.do
  2. Request Method:post
  3. Status code:200 OK
  4. Request Headers
  5. accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
  6. Accept-encoding:gzip,deflate,sdch
  7. accept-language:zh-cn,zh;q=0.8,en;q=0.6
  8. alexatoolbar-alx_ns_ph:alexatoolbar/alxg-3.2
  9. Cache-control:max-age=0
  10. Connection:keep-alive
  11. Content-length:25
  12. content-type:application/x-www-form-urlencoded
  13. cookie:jsessionid=74ac93f9f572980b6fc10474cd8edd8d
  14. host:127.0.0.1:8080
  15. origin:http://127.0.0.1:8080
  16. referer:http://127.0.0.1:8080/test/index.jsp
  17. user-agent:mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.149 safari/537.36
  18. Form Data
  19. Name:mikan
  20. Address:street
  21. Response Headers
  22. Content-length:2
  23. Date:sun, 11:05:33 GMT
  24. server:apache-coyote/1.1

Note here that the content-type of the POST request is application/x-www-form-urlencoded, and the parameter is in the request body, which is the form Data in the request above.

In a servlet, form parameters can be obtained in the form of Request.getparameter (name).

And if you use the native Ajax POST request:

[JavaScript] view plain copy

  1. function getxmlhttprequest () {
  2. var xhr;
  3. if (Window. ActiveXObject) {
  4. xhr= New ActiveXObject ("Microsoft.XMLHTTP");
  5. }Else if (window. XMLHttpRequest) {
  6. xhr= New XMLHttpRequest ();
  7. }Else {
  8. xhr= null;
  9. }
  10. return xhr;
  11. }
  12. function Save () {
  13. var xhr = Getxmlhttprequest ();
  14. Xhr.open ("Post", "http://127.0.0.1:8080/test/test.do");
  15. var data = "Name=mikan&address=street ...";
  16. Xhr.send (data);
  17. xhr.onreadystatechange= function() {
  18. if (Xhr.readystate = = 4 && xhr.status = = 200) {
  19. Alert ("Returned:" + Xhr.responsetext);
  20. }
  21. };
  22. }

The request header is shown by Chrome's developer tool as follows:

[plain] view plain copy

  1. Requesturl:http://127.0.0.1:8080/test/test.do
  2. Request Method:post
  3. Status code:200 OK
  4. Request Headers
  5. accept:*/*
  6. Accept-encoding:gzip,deflate,sdch
  7. accept-language:zh-cn,zh;q=0.8,en;q=0.6
  8. alexatoolbar-alx_ns_ph:alexatoolbar/alxg-3.2
  9. Connection:keep-alive
  10. Content-length:28
  11. Content-type:text/plain;charset=utf-8
  12. Cookie:jsessionid=c40c7823648e952e7c6f7d2e687a0a89
  13. host:127.0.0.1:8080
  14. origin:http://127.0.0.1:8080
  15. referer:http://127.0.0.1:8080/test/index.jsp
  16. user-agent:mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.149 safari/537.36
  17. Request Payload
  18. Name=mikan&address=street
  19. Response Headers
  20. Content-length:2
  21. Date:sun, 11:49:23 GMT
  22. server:apache-coyote/1.1

Note The requested Content-type is Text/plain;charset=utf-8, and the request form parameter is in Requestpayload.

Then the servlet passed Request.getparameter (name) is empty. Why is it? And how should such parameters be obtained?

In order to understand this problem, looked up some information, also read the Tomcat7.0.53 about the request parameter processing source code, finally figured out what is going on.

When an HTTP post form requests a commit, the content-type used is application/x-www-form-urlencoded, and the POST request that uses the native AJAX does not specify the request header Requestheader, The default content-type used is text/plain;charset=utf-8.

Because Tomcat has "special handling" for Content-type multipart/form-data (file upload) and application/x-www-form-urlencoded (POST request). Here's a look at the related processing code.

The implementation class for Tomcat's HttpServletRequest class is org.apache.catalina.connector.Request (actually org.apache.coyote.Request), and its method for processing request parameters is PROTECTE d void Parseparameters (), this method for Content-type multipart/form-data (file upload) and application/ The processing code for the x-www-form-urlencoded (POST request) is as follows:

[Java] view plain copy

  1. Protectedvoid Parseparameters () {
  2. Omit part of the code ...
  3. Parameters.handlequeryparameters ();//This is the processing of the parameters in the URL
  4. Omit part of the code ...
  5. if ("Multipart/form-data". Equals (ContentType)) {//Here is processing file upload request
  6. Parseparts ();
  7. Success = true;
  8. return;
  9. }
  10. if (! ("application/x-www-form-urlencoded". Equals (ContentType))) {//here if the non-POST request is returned directly, no longer processed
  11. Success = true;
  12. return;
  13. }
  14. The following code is the processing of the POST request parameters
  15. Omit part of the code ...
  16. Try {
  17. if (Readpostbody (FormData, len)! = len) {//Read request body Data
  18. return;
  19. }
  20. } catch (IOException e) {
  21. Client Disconnect
  22. if (Context.getlogger (). isdebugenabled ()) {
  23. Context.getlogger (). Debug (
  24. Sm.getstring ("Coyoterequest.parseparameters"), e);
  25. }
  26. return;
  27. }
  28. Parameters.processparameters (formData, 0, Len); Process the POST request parameter and put it in the Requestparameter map (that is, Request.getparametermap gets the Map,request.getparameter (name) from this map)
  29. Omit part of the code ...
  30. }
  31. protected int readpostbody (byte body[], int len)
  32. throws IOException {
  33. int offset = 0;
  34. Do {
  35. int Inputlen = GetStream (). Read (body, offset, len-offset);
  36. if (Inputlen <= 0) {
  37. return offset;
  38. }
  39. Offset + = Inputlen;
  40. } while ((Len-offset) > 0);
  41. return Len;
  42. }


As can be seen from the above code, Content-type is not a application/x-www-form-urlencoded POST request is not to read the request body data and the corresponding parameter processing, that is, the form data will not be parsed into the request Parameter map. So through Request.getparameter (name) is not available.

So how do we get the arguments that are submitted?

Of course it is the most primitive way to read the input stream to get it, as shown below:

[Java] viewplain copy

  1. Privatestring Getrequestpayload (HttpServletRequest req) {
  2. STRINGBUILDERSB = new StringBuilder ();
  3. Try (Bufferedreaderreader = Req.getreader ();) {
  4. Char []buff = new char[1024];
  5. Intlen;
  6. while (len = reader.read (buff))! =-1) {
  7. Sb.append (buff,0, Len);
  8. }
  9. }catch (IOException e) {
  10. E.printstacktrace ();
  11. }
  12. Returnsb.tostring ();
  13. }

Of course, the POST request setting up application/x-www-form-urlencoded can also be obtained in this way.

Therefore, when using the native Ajax POST request, you need to explicitly set the request Header, which is:

[JavaScript] viewplain copy

    1. Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

In addition, if I use jQuery, I use 1.11.0 this version to Test , $.ajax POST request is not need to explicitly set this request header, other version of I did not personally tested. It is believed that the version after 1.11.0 is also not required to be set. But it doesn't have to be before. This has not been tested.

2015-04-17 PostScript:

Recently in Reading, really understand, why the server will be the form submission and file upload do special processing, because the form submission data is the way of name value pairs, and Content-type is application/x-www-form-urlencoded, The file upload server needs special processing, the normal POST request (Content-type is not application/x-www-form-urlencoded) data format is not fixed, not necessarily the way of the name value pairs, so the server can not know the specific processing method, Therefore, parsing can only be done by acquiring the original data stream.

jquery sets Content-type to application/x-www-form-urlencoded when executing a POST request, so the server can parse correctly, and when using native AJAX requests, If the settings are not displayed Content-type, then the default is Text/plain, then the server does not know how to parse the data, so only by acquiring the original data stream to parse the request data.

When the background uses @requestbody to receive data as an object, the foreground must be passed as Application/json, using json.stringify (data) to convert the JSON object to a JSON string.

When you use the application/x-www-form-urlencoded format to pass data, Tomcat assembles it into a map that can only be accessed by Request.getparameter in the background.

Native AJAX default format: Text/plain

Jquery ajax default Format (MAP) + form form Post submission format: application/x-www-form-urlencoded

Character Stream Ajax Format (MAP): Application/json (using json.stringify (data) to convert a JSON object to a JSON string)

File Upload: Multipart/form-data

Ajax's Text/plain, application/x-www-form-urlencoded, and Application/json

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.