我有一个在Wildfly 8上运行的RESTful WebService。 测试@GET工作得很好,但@POST不接受我的JSON对象。 我很难找出代码中的错误,我非常感谢您的帮助!代码中的错误在哪里?RESTful WebService不接受@POST?
报告实体:
@Entity
@XmlRootElement
public class Report implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlAttribute
private Long id;
@NotNull
private String reportContent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getReportContent() {
return reportContent;
}
public void setReportContent(String reportContent) {
this.reportContent = reportContent;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Report)) {
return false;
}
Report other = (Report) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.myprog.abc.domain.Report[ id=" + id + " ]";
}
}
报告资源:
@Path("report")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReportResource {
@EJB
private ReportService rs;
@GET
public Response findReports() {
final List<Report> reports = rs.findAllReports();
if(reports.size() <= 0)
throw new NotFoundException("No reports found.");
return Response.ok(new GenericEntity<List<Report>>(reports) {})
.build();
}
@GET
@Path("{id:[1-9][0-9]*}")
public Response findReport(@PathParam("id") Long id) {
Report report = rs.findReport(id);
if(report == null)
throw new NotFoundException("No report found having the id " + id + ".");
return Response.ok(report)
.build();
}
@POST
public Response createReport(@Valid Report report) {
rs.saveReport(report);
return Response.created(URI.create("/" + report.getId()))
.build();
}
}
测试时使用http://localhost:8080/abc/rest/report/123
服务器返回@GET:
{"reportContent":"This is my Report test content!","id":123}
当使用http://localhost:8080/abc/rest/report
测试@POST和{“reportContent”:“这是我的报告测试内容!”}服务器返回:
Status Code: 415 Unsupported Media Type
Connection: keep-alive
Content-Length: 0
Date: Tue, 07 Oct 2014 14:04:55 GMT
Server: WildFly/8
x-powered-by: Undertow/1
我的问题是为什么你需要发布?是否有任何特定的需求,您无法使用get?我知道我的JSON数据,我保持GET,尤其是因为我看到的只是你请求数据,你实际上是在修改什么? – DreadHeadedDeveloper 2014-10-07 14:21:51
其实,这里有一个链接,可以帮助一些http://stackoverflow.com/questions/7160526/jquery-getjson-vs-post-which-one-is-faster – DreadHeadedDeveloper 2014-10-07 14:26:30
好吧,问题解决了设置标题。代码因此非常好。虽然我没有看到任何理由,我应该把所有的数据放在一个GET行中,而不是将它们全部隐藏在POST中。我明白,两者都有效,但你会在GET中看到哪些优势? – Socrates 2014-10-07 15:34:04