原文地址: http://www.cnblogs.com/tugenhua0707/p/8975615.html
FormData和Payload是浏览器传输给接口的两种格式,这两种方式浏览器是通过Content-Type来进行区分的(了解Content-Type),如果是 application/x-www-form-urlencoded的话,则为formdata方式,如果是application/json或multipart/form-data的话,则为 request payload的方式。
比如如下使用ajax方式的提交post请求的代码(默认使用application/x-www-form-urlencoded编码):
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"> <script type="text/javascript" src="https://tugenhua0707.github.io/html5UploadImage/js/jquery.js"></script> </head> <body> <div id="app"> <div class="btn">发送post请求</div> </div> <script> var obj = { "name": 'CntChen', "info": 'Front-End', }; $('.btn').click(function() { $.ajax({ url: 'www.example.com', type: 'POST', dataType: 'json', data: obj, success: function(d) { } }) }); </script> </body> </html>
如下图所示:
2. 使用 multipart/form-data表单上传文件
如下html代码:
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"> </head> <body> <div id="app"> <form action="http://www.example.com" method="POST" enctype="multipart/form-data"> <p>username: <input type="text" name="fname" /></p> <p>age: <input type="text" name="age" /></p> <input type="submit" value="提交" /> </form> </div> </body> </html>
如下图所示:
可以看到 使用multipart/form-data表单上传文件时使用的是 Request Payload 格式;
3. 使用 Content-Type: application/json 来编码
如下html代码:
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"> <script type="text/javascript" src="https://tugenhua0707.github.io/html5UploadImage/js/jquery.js"></script> </head> <body> <div id="app"> <div class="btn">发送post请求</div> </div> <script> $('.btn').click(function() { $.ajax({ url: 'http://localhost:8081/api.json', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify({a: [{b:1, a:1}]}), success: function(d) { } }) }); </script> </body> </html>
如下图所示
-
如果请求头里设置Content-Type: application/x-www-form-urlencoded,那么这个请求被认为是表单请求,参数出现在Form Data里,格式为key=value&key=value&key=value...。后端可以通过request.getParameter(name)的形式来获取表单参数。
-
原生的AJAX请求头里设置Content-Type:application/json,或者使用默认的请求头Content-Type:text/plain;参数会显示在Request payload块里提交。
后端可以通过request.getParameter(name)的形式来获取表单参数。
private String getStringFromStream(HttpServletRequest req) { ServletInputStream is; try { is = req.getInputStream(); int nRead = 1; int nTotalRead = 0; byte[] bytes = new byte[10240]; while (nRead > 0) { nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead); if (nRead > 0) nTotalRead = nTotalRead + nRead; } String str = new String(bytes, 0, nTotalRead, "utf-8"); return str; } catch (IOException e) { e.printStackTrace(); return ""; } }