Java RESTful Web服务无法正确处理请求方法

Java RESTful Web服务无法正确处理请求方法,java,rest,request,jax-rs,Java,Rest,Request,Jax Rs,我正在从多个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); }

我正在从多个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}参数(如代码中所示)

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

更新

因为createPerson是空的,所以我不处理连接。getInputStream()。 这实际上似乎导致我的服务无法处理请求

但是实际的请求是在连接上发送的。getOutputStream(),对吗

更新2

只要我处理一个带有返回值的方法,从而处理connection.getOutputStream(),RequestMethod就可以工作。当我尝试调用一个void并因此不处理connection.getOutputStream()时,服务将不会收到任何请求。

您应该设置“内容类型”而不是“接受”标题。内容类型指定发送给收件人的媒体类型,而Accept是指客户端接受的媒体类型。有关标题的更多详细信息,请参阅

以下是Java客户端:

public static void main(String[] args) throws Exception {
    String data = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><person><name>1234567</name></person>";
    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();
}
,其中“person”是包含xml的文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><name>1234567</name></person>
1234567

如果使用cURL怎么办<代码>curl-X POSThttp://localhost:8080/RESTfulService/service/person尝试从您的请求中删除accept标头。我对此不确定。试图帮助你调试。我们需要弄清楚为什么要调用GET。那么序列是否重要呢?可能GET是“/person”url模式的第一个匹配项,我认为用JAX-RS注释的方法必须返回一些东西。尝试用字符串替换void返回类型并返回任何内容。我可以确认删除accept头不会有任何区别。或者您也可以将@products(“application/xml”)@Consumes(“application/xml”)添加到这两个方法中,然后重试。我认为在这种情况下它也需要运行。HTTP连接有一个请求和响应,所以我认为您需要读取响应。同样,一个方法将返回关于其成功的某种状态,然后读取响应将更有意义,这将是一件好事。
curl -X POST -d @person --header "Content-Type:application/xml" http://localhost:8080/RESTfulService/service/person
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><name>1234567</name></person>