application / x-www-form-urlencoded and multipart / form-data and application / json distinction fine analysis

1. due

  Internet can not find the application / x-www-form-urlencoded and multipart / form-data and application / json fully explain the difference between the three articles, I am really disappointed, idiopathic this post detailed explanation.

  When the front end of data transfer to the back, needs to be encoded, wherein the coding format can be divided into four categories: application / x-www-form-urlencoded, multipart / form-data, application / json, text / plain.

  text / plain plain text data, no explanation here, usually no one will use.

  Taiwan before and after the completion of data exchange are only two ways: First, form submission form, and second, ajax submit.

  form form enctype attribute may be provided by an encoding type, the default value: application / x-www-form-urlencoded; ajax coding type can be set, the default values ​​are contentType property: application / x-www-form-urlencoded;

2.application/x-www-form-urlencoded

  How to use the backstage reception request.getParameter ( "work");? To get the parameter name and value.

  This encoding format is the most common one way, the data is encapsulated into a string, the parameter name and parameter value using the "=" splice, using the "&" between the splice parameter final delivery to the background data have the form : key1 = value1 & key2 = value2 & ...;

  Further, key and value are respectively using the encodeURI () be encoded, i.e. the data you want to pass, in fact, has been a coding of the form: name = Marydon & work =% E7% A8% 8B% E5% BA% 8F% E5% 91% 98, after the server receives the first thing is to use a dry URLDdecoder.decode () the name and value of the once decoded.

  Whether or ajax request form request form, so that the data are assembled.

  The basic difference between post get request requests:

  This is a get request

  The figure is a post request

  The difference is: get requests directly spliced ​​form data to the url with? Apart, the external data visible; the post request into a data request body will not directly see the data to be transmitted, the security is relatively higher.

  PS: you want to compare two requests difference in the IE browser to debug the most intuitive, chrome not.

  This is the difference between the two well-known for our public, then the question is, why get requests submitted data when carrying Chinese background Chinese data received will be messy, but the request will not be garbled post it?

  Then look at these two requests:  

  get request

  post request

  The request background characters printed

// character set is the request 
System.out.println (request.getCharacterEncoding ());  

  Before and after the test ends, this time we can see the difference between post get to request another request:

  When is application / x-www-form-urlencoded (i.e. default), the browser sends a request back to the form in the form of data encoding type is provided, it is divided into two cases:

  When the request for the mode get, no request header Content-Type attribute information, there is no character set designating data;

  When the request is a POST mode, there is a request header Content-Type attribute information, and to specify the character set of the data, namely: application / x-www-form-urlencoded; charset = UTF-8;

  When you get a request, the character set used in the end what is? The outcome by background tests: ISO-8859-1

// get the default character set request 
String work = new String (work.getBytes ( "iso-8859-1"), "utf-8");

  So being the case, in ajax request, we can not explicitly declare contentType attribute request to solve the garbage problem get it?

type: 'get', // request method 
contentType: 'application / x-www -form-urlencoded; charset = UTF-8', // explicitly declare

  Page in force

  The results have been disappointing:

  Or distortion, had to re-encode. 

  Content-Type attribute tells the server character set data submitted is utf-8, and allow the server to parse utf-8 format data, we can see:

  The problem is not the server, and wherein the browser: when the browser detects that the encoding format is application / x-www-form-urlencoded and is a get request, the browser first encodes the data form with ISO-8859-1, and then encodeURI () encoded.

  So, get the background leading to the request received by Chinese garbled the root cause: page character set is utf-8, but the browser according to recode iso-8859-1, backstage after receiving the order to decode utf-8 course will garbled.

  summary:

  When the coding format of the form data: when application / x-www-form-urlencoded:

  get request, the browser will be re-encoded data according to iso-8859-1, inevitably resulting in a background received garbled Chinese;

  post request, the browser will submit the data to be encoded as utf-8, because the background itself is to use utf-8 parses it, so it will not appear garbled situation.

  As to get a request to solve the garbage problem There are two main ways, I see another article.

3.multipart/form-data

  Mainly used for file transfer, the file converted into binary data for transmission does not involve problems transcoding.

  How to use the backstage reception request.getInputStream ();? Value.

  IE and the browser chrome, form of data transmission is not the same;

  IE browser

  chrome browser 

  Common is: Content-Type value multipart / form-data; boundary = --..., seemingly no other fixed format, is no longer considered, as long as the background on the line received.

  Background of the received data, like this:

  Binding code implementation: 

  The front end transmission data

<input type="file" id="file" onchange="upload('getParams')" style="display: none;">
<input type="button" value="上传" onclick='javascript:$("#file").click()'>  
Upload function (URL) { 
    // Get JS file object 
    var fileObj = document.getElementById ( "File") Files [0];. 
    IF (fileObj == null) { 
        Alert ( "image upload. Please try again!") ; 
        return; 
    } 
    // Create a form form 
    var FormFile the FormData new new = (); 
    // Add file object 
    formFile.append ( "file", fileObj); 
    // Create an XMLHttpRequest object 
    var XHR = new new XMLHttpRequest (); 
    // POST mode , url requests for the server address, true this parameter specifies whether the request is asynchronous processing. 
    xhr.open ( "POST", URL, to true); 
    // request is completed 
    xhr.onload = function () { 
        // returns the data into a JSON object 
        var = ResData the JSON.parse (this.responseText); 
        document.getElementById ( "file"). 
    }; 
    // Request failed 
    Xhr.onerror = null; 
    // call the method upload progress (progress bar may be implemented upload) 
    xhr.upload.onprogress = null; 
    // // start uploading, data transmission form (binary data to pass to the background) 
    xhr.send (FormFile); 
}

  Background reception

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    InputStream is = request.getInputStream();
    int i = 0;
    while ((i = is.read()) != -1) {
        System.out.print((char) i);
    }
}

4.application/json

  How backstage reception? Use request.getReader () value can also be used request.getInputStream () Gets.

  Examples of errors:

.ajax $ ({ 
	type: 'POST', // mode request 
	url: 'getParams', // address request 
	contentType: 'file application / JSON; charset = UTF-. 8', 
	Data: { 'name': 'Marydon', 'work': 'programmer'}, 
	success: function (Result) {// request is successful 
		Alert (result.work); 
	} 
});

  The results form the data was submitted in the form of a form, is not json

  Data transmissions in json format, sent from the front end in the form of json unusual manner, it is common to the server, i.e. a server json transmitted data from the server, another server receives his.

  Closer to home, how to pass data to the background transfer ajax json it?

  You first need to understand is that the front end to the back-end data transmission and there are only two ways, one is the common string format, while another is binary data, that is, no matter what type of data will transfer you to the background is converted into characters string or binary.

  In this way, we understand, to the background transfers, not passing a json object, but should pass a json string.

  And the difference between ordinary Ajax call, just that: parameter name, that name needs single quotes, {} on both sides to be in quotes, so that you do not need to use the backslash \ to escape it.

  Code

.ajax $ ({ 
	type: 'POST', // mode request 
	url: 'getParams', // request address 
	contentType: 'application / json; charset = UTF-8', // tells the server, data transfer is json ( may be omitted) 
	Data: "{ 'name': 'Marydon', 'Work': 'programmer'}", // json string (requirement) 
	success: function (Result) {// request is successful 
		alert (result. Work); 
	} 
});  

  Background reception: There are two ways

  Method 1: Use a character stream value -request.getReader ()

StringBuffer buffer = new StringBuffer();
BufferedReader reader = request.getReader();
String s = "";
while ((s = reader.readLine()) != null) {
    buffer.append(s);
}
System.out.println(JSONObject.fromObject(buffer.toString()));
System.out.println(buffer.toString());  

  Second way: a byte stream value -request.getInputStream ()

int i = 0;
StringBuffer buffer = new StringBuffer();
InputStream stream = request.getInputStream();
while ((i = stream.read()) != -1) {
    buffer.append((char)i);
}
System.out.println(JSONObject.fromObject(buffer.toString()));
System.out.println(buffer.toString());

  Print results

  After testing found that even Ajax does not declare contentType, which is the default value used: application / x-www-form-urlencoded, when you are actually transmitted json string, the background still can be received normally. As shown below:

  Although the background can normally receive, however, in order to standardize act or statement on it. 

  Further, as you can see when you want to transfer the background json string, you will commit the same problems get request: Chinese When the parameter value, the received background data will be garbled, manually transcoding.

  There are two ways to solve the garbage, not repeat them here, other articles have detailed explanation. 

  

Written in the last

  Which big brother If it is found there is leakage of the carelessness of the article or need to add more content, welcome message! ! !

 related suggestion:

 

Guess you like

Origin www.cnblogs.com/Marydon20170307/p/12621036.html