jquery ajax 用 data 和 headers 向 java RESTful 传递参数区别

时间:2023-12-15 19:29:50

jquery 的 ajax 是非常方便的一个函数,记录一下 $.ajax 生成的 http 报文

一、使用 data 传递参数:

 $.ajax({
url : "webrs/test/addBook",
type : "POST",
data:{
id : "xx",
name : "中",
price : "xx"
}, contentType: "text/plain; charset=utf-8"
});

此时生成的 http 报文类似于下面这样:

POST /WS_BookStore/faces/webrs/test/addBook HTTP/1.1 (CRLF)
Host: localhost:8080 (CRLF)
Connection: keep-alive (CRLF)
Content-Length: 22 (CRLF)
Pragma: no-cache (CRLF)
Cache-Control: no-cache (CRLF)
Accept: */* (CRLF)
Origin: http://localhost:8080 (CRLF)
X-Requested-With: XMLHttpRequest (CRLF)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 (CRLF)
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 (CRLF)
Referer: http://localhost:8080/WS_BookStore/faces/deleteBook.html (CRLF)
Accept-Encoding: gzip, deflate, br (CRLF)
Accept-Language: zh-CN,zh;q=0.8 (CRLF)
Cookie: JSESSIONID=ab94dd581643b1b96e0190c3bbeb (CRLF)
(CRLF) //该CRLF表示消息报头已经结束,在此之前为消息报头
id=xx&name=%E4%B8%AD&price=xx

参数在 http 的正文部分,在 RESTful 中使用注解 @FormParam 可以获取到此参数

 @POST
@Produces("application/json; charset=UTF-8")
@Path("addBook")
public String addBook(@FormParam("id") int BookID, @FormParam("name") String BookName, @FormParam("price") int Price) {
// ...
}

二、使用 headers 传递参数

 $.ajax({
url : "webrs/test/addBook",
type : "POST",
headers:{
id : "xx",
name : "xx",
price : "xx"
}, contentType: "text/plan; charset=utf-8"
});

此时生成的 http 报文类似于下面这样:

POST /WS_BookStore/faces/webrs/test/addBook HTTP/1.1 (CRLF)
Host: localhost:8080 (CRLF)
Connection: keep-alive (CRLF)
Content-Length: 0 (CRLF)
Pragma: no-cache (CRLF)
Cache-Control: no-cache (CRLF)
Origin: http://localhost:8080 (CRLF)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
id: xx (CRLF) // 注意参数 id 在这里
Content-Type: text/plan; charset=utf-8 (CRLF)
Accept: */* (CRLF)
X-Requested-With: XMLHttpRequest (CRLF)
name: xx (CRLF) // 注意参数 name 在这里
price: xx (CRLF) // 注意参数 price 在这里
Referer: http://localhost:8080/WS_BookStore/faces/deleteBook.html (CRLF)
Accept-Encoding: gzip, deflate, br (CRLF)
Accept-Language: zh-CN,zh;q=0.8 (CRLF)
Cookie: JSESSIONID=ab94dd581643b1b96e0190c3bbeb (CRLF)

参数在 http 的报头部分,在 RESTful 中使用注解 @HeaderParam 可以获取到此参数

 @POST
@Produces("application/json; charset=UTF-8")
@Path("deleteBook")
public String deleteBook(@HeaderParam("id") int BookID) {
// ...
}