[英]RESTful WebService does not accept @POST?
我在Wildfly 8上運行了一些RESTful WebService。測試@GET可以很好地工作,但是@POST將不接受我的JSON對象。 我很難找出代碼中有什么問題,非常感謝您的幫助! 代碼中的錯誤在哪里?
報告實體:
@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
和{“ reportContent”:“這是我的Report測試內容!”}測試@POST時,服務器返回:
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
我使用jaxrs Client API測試了您的示例:
Client client = ClientBuilder.newClient();
WebTarget myResource = client.target("http://localhost:8080/web/rest/report");
Report m = new Report();
m.setId((long) 12);
m.setReportContent("asdf");
Entity<Report> report = Entity.json(m);
Response r = myResource.request(MediaType.APPLICATION_JSON).post(report);
System.out.println(r.getHeaderString("Location"));
最后,它在“響應位置”標頭中為我提供了適當的值。
確保您的請求中包含標題Content-type
。 該值必須為application/json
,因為這是您期望的值。
我很確定您會錯過它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.