所以,我正在尝试创建一个简单的(我的意思是简单的)POST 请求。这是服务器端的类。
@Stateless
@Path("cards")
public class CardsFacadeREST extends AbstractFacade<Cards> {
@POST
@Path("test")
@Consumes({"text/plain"})
public void createTestCard() {
Cards card = new Cards();
card.setName("Test Card");
super.create(card);
}
@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
}
GET 方法工作得很好,但 POST 方法对我不起作用。我正在使用 Chrome 的高级 Rest 客户端。
- 网址为 http://localhost:8080/dc-rest/webresources/cards/test
- 类型为 POST
- 我的标题如下:内容类型:text/plain
就是这样。
我不断收到“400:错误请求。客户端发送的请求在语法上不正确。”
当我在 JSON 窗口中打开响应时,它只显示“意外 token <”
以下是请求 header (如果有任何区别)。
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: text/plain
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=f4c746a32b46244d422800192f04; treeForm_tree- hi=treeForm:tree:applications
Body is empty.
响应:
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)
Server: GlassFish Server Open Source Edition 4.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Allow: GET,DELETE,OPTIONS,PUT,POST
Access-Control-Allow-Headers: content-type
Content-Language:
Content-Type: text/html Date: Thu, 11 Feb 2016 20:48:12 GMT
Connection: close Content-Length: 1105
Body:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>GlassFish Server Open Source Edition 4.0 - Error report</title><style type="text/css"><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 400 - Bad Request</h1><hr/><p><b>type</b> Status report</p><p><b>message</b>Bad Request</p><p><b>description</b>The request sent by the client was syntactically incorrect.</p><hr/><h3>GlassFish Server Open Source Edition 4.0 </h3></body></html>
最佳答案
400-Bad 请求响应可能是因为服务器已表示它需要特定的内容类型
@Consumes({"text/plain"}
但是,客户端并未表明帖子正文属于这种类型。
要解决此问题,请确保来自客户端的 POST 请求包含以下 HTTP header :
Content-Type: text/plain
或者,也许您不是 POST 纯文本,而是打算 POST XML 或 JSON。无论预期的类型是什么,您只需要确保客户端和服务器对此达成一致即可。
关于java - 向 REST 服务器发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35349792/