Post请求包含请求头和请求行
Post常用的请求体(body)有三种传输内容类型(Content-type): application/x-www-form-urlencoded、application/json、application/form-data,当然还有其他的几种,常用的是这三种。
No1: application/x-www-form-urlencoded
通过Postman可以看到Post请求的参数一般放在Body里。我们的application/x-www-form-urlencoded方式也是Post请求最早支持的一种数据传输方式,这种也是key和value形式,将我们的参数类似于GET方式那样拼接成一个字符串,例如:key1=value1&key2=value2,这种形式,然后将这个参数字符串进行urlencode编码,放到Body里进行发送请求数据。
接下来分别用Java Spring MVC、JS Ajax分别演示下这种方式的请求和接口编写:
- 在Java的Spring MVC中默认的编写Controller接口请求数据传输就是这种方式:application/x-www-form-urlencoded。
package com.web.mvc.controller;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.web.mvc.model.Entity;
import com.web.mvc.model.User;
import com.web.mvc.service.EntityService;
import com.web.mvc.service.IEntityService;
import com.web.mvc.utils.RedisUtils;
import com.web.mvc.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
//@Controller
@RestController
@RequestMapping("/entity")
public class EntityController {
@Autowired
private IEntityService entityService;
//默认form-urlcoded
@CrossOrigin
@RequestMapping(value = "/urlcodedReq", method = RequestMethod.POST)
@ResponseBody
public String urlcodedReq(@RequestParam String name,
@RequestParam String pwd) {
System.out.println("urlcodedReq:" + name + " " + pwd);
Gson gson = new Gson();
HashMap<String, String> map = new HashMap<>();
map.put("name", name);
map.put("pwd", pwd);
return gson.toJson(map);
}
}
@CrossOrigin:用来处理支持跨域请求的;
@ResponseBody:作用在方法上,表示请求返回的数据写入http response body里,也就是返回数据,而不是进行页面跳转。
以上就是Java Spring MVC编写Controller Post接口的写法。
- Jquery Ajax写法:
function getOrigantAjaxPost() {
var stringData = 'name=value1&pwd=value2'
$.ajax({
data: stringData,
async: true,
url: 'http://' + hostName + ':' + port + '/entity/urlReq',
type: "post",
processData: false, //tell jQuery not to process the data
contentType: "application/x-www-form-urlencoded",
success: function (data, status) {
// alert("Data: " + status);
console.log("Data: " + JSON.stringify(data) + " " + status);
},
error: function (e) {
// alert("Data: error" + JSON.stringify(e));
console.log('error ' + JSON.stringify(e));
}
});
}
No2: application/json
application/json也就是告诉我们的服务器我们的消息体内容类型是序列化的JSON字符串,例如:{ "name": "value1", "pwd": "value2" }。获取到这个body直接解析Json格式字符串即可拿到参数数据。
接下来分别用Java Spring MVC、JS Ajax分别演示下这种方式的请求和接口编写:
- 在Java的Spring MVC中编写Controller接口接收解析application/json这种数据格式的需要在注解里定义consumes和produces为application/json类型。
@CrossOrigin
@RequestMapping(value = "/req", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE
, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String postReq(@RequestBody User user) {
System.out.println("req:" + user.getName() + " " + user.getPwd());
Gson gson = new Gson();
HashMap<String, String> map = new HashMap<>();
map.put("name", user.getName());
map.put("pwd", user.getPwd());
return gson.toJson(map);
}
- Ajax的请求:
/**
* 原生Ajax POST请求
*/
function getOrigantAjaxPost() {
var postData = '{ "name": "value1", "pwd": "value2" }';
var oAjax = null;
//这里进行HTTP请求
try {
oAjax = new XMLHttpRequest();
} catch (e) {
oAjax = new ActiveXObject("Microsoft.XMLHTTP");
};
//post方式
oAjax.open('post', 'http://' + hostName + ':' + port + '/entity/req', true);
oAjax.setRequestHeader("Content-type", "application/json");
//post发送数据
oAjax.send(postData);
oAjax.onreadystatechange = function () {
//当状态为4的时候,执行以下操作
if (oAjax.readyState == 4 && oAjax.status == 200) {
try {
//+ oAjax.responseText
console.log('tryForm:' + oAjax.responseText);
// alert('readyState' + oAjax.status + " "
// + oAjax.responseText);
} catch (e) {
// alert('你访问的页面出错了' + e);
};
};
};
No3: application/form-data
这种格式主要用来进行文件上传,当然可以作为表单内容进行键值对提交数据,各个表单项之间用boundary分开。
接下来分别用Java Spring MVC、JS Ajax分别演示下这种方式的请求和接口编写:
- 在Java的Spring MVC中编写Controller接口接收解析multipart/form-data这种数据格式的需要在注解里定义consumes和produces为multipart/form-data类型。
@CrossOrigin
@RequestMapping(value = "/upReq", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public String uploadReq(@RequestPart(value = "file") MultipartFile multipartFile,
@RequestParam("description") String description) {
String fileType = multipartFile.getContentType();
String fileName = multipartFile.getOriginalFilename();
File file = new File("E:/file.jpg");
System.out.println("请求:" + fileType + " "
+ fileName + " " + description);
try {
multipartFile.transferTo(file);
return "success";
} catch (IOException e) {
e.printStackTrace();
return "failure";
}
}
@CrossOrigin
@RequestMapping(value = "/formReq", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public String formDataReq(@RequestParam String name,
@RequestParam String pwd) {
System.out.println("formReq:" + name + " " + pwd);
Gson gson = new Gson();
HashMap<String, String> map = new HashMap<>();
map.put("name", name);
map.put("pwd", pwd);
return gson.toJson(map);
}
- Ajax请求:
/**
* 原生Ajax POST请求
*/
function getOrigantAjaxPost() {
var oAjax = null;
//这里进行HTTP请求
try {
oAjax = new XMLHttpRequest();
} catch (e) {
oAjax = new ActiveXObject("Microsoft.XMLHTTP");
};
var formData = new FormData();
formData .append("file", file); // 文件对象
formData .append("description", "description");
//post方式
oAjax.open('post', 'http://' + hostName + ':' + port + '/entity/formReq', true);
// oAjax.setRequestHeader("Content-type", "multipart/form-data");
//post发送数据
oAjax.send(formData );
oAjax.onreadystatechange = function () {
//当状态为4的时候,执行以下操作
if (oAjax.readyState == 4 && oAjax.status == 200) {
try {
//+ oAjax.responseText
console.log('tryForm:' + oAjax.responseText);
// alert('readyState' + oAjax.status + " "
// + oAjax.responseText);
} catch (e) {
// alert('你访问的页面出错了' + e);
};
};
};
}