RESTful Webservice无法正确处理Request Method

我正在从多个RESTful Web服务方法中检索值。 在这种情况下,由于请求方法的问题,两种方法相互干扰。

@GET @Path("/person/{name}") @Produces("application/xml") public Person getPerson(@PathParam("name") String name) { System.out.println("@GET /person/" + name); return people.byName(name); } @POST @Path("/person") @Consumes("application/xml") public void createPerson(Person person) { System.out.println("@POST /person"); System.out.println(person.getId() + ": " + person.getName()); people.add(person); } 

当我尝试使用以下代码调用createPerson()方法时,我的Glassfish服务器将导致“@GET / person / 我试图创建一个人的名字 ”。 这意味着调用了@GET方法,即使我没有发送{name}参数(正如您在代码中看到的那样)。

 URL url = new URL("http://localhost:8080/RESTfulService/service/person"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/xml"); connection.setDoOutput(true); marshaller.marshal(person, connection.getOutputStream()); 

我知道这需要大量挖掘我的代码,但在这种情况下我做错了什么?

UPDATE

因为createPerson是一个void,所以我不处理connection.getInputStream()。 这实际上似乎导致我的服务不处理请求。

但实际请求是在connection.getOutputStream()上发送的,对吗?

更新2

RequestMethod确实有效,只要我处理一个带有返回值的方法,从而处理connection.getOutputStream()。 当我尝试调用void而不处理connection.getOutputStream()时,服务将不会收到任何请求。

您应该设置“Content-Type”而不是“Accept”标头。 Content-Type指定发送给收件人的媒体类型,而Accept是关于客户端接受的媒体类型。 标题的更多细节在这里 。

这是Java客户端:

 public static void main(String[] args) throws Exception { String data = "1234567"; URL url = new URL("http://localhost:8080/RESTfulService/service/person"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/xml"); connection.setDoOutput(true); connection.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); wr.close(); rd.close(); connection.disconnect(); } 

这是使用curl相同的:

 curl -X POST -d @person --header "Content-Type:application/xml" http://localhost:8080/RESTfulService/service/person 

,其中“person”是包含xml的文件:

 1234567