在Jersey Java中向REST WebService发送和接收JSON

在Jersey Java中向REST WebService发送和接收JSON,java,web-services,rest,jersey,jersey-client,Java,Web Services,Rest,Jersey,Jersey Client,我是新泽西Java REST WebService框架的开发者。我正在尝试编写一个使用和生成JSON的服务方法。我的服务代码如下。这是最简单的代码,只是为了学习 @Path("/myresource") public class MyResource { @Path("/sendReceiveJson") @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON

我是新泽西Java REST WebService框架的开发者。我正在尝试编写一个使用和生成JSON的服务方法。我的服务代码如下。这是最简单的代码,只是为了学习

@Path("/myresource")
public class MyResource {

    @Path("/sendReceiveJson")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String sendReceiveJson(String name)
    {
        System.out.println("Value in name: " + name);
        return "{\"serviceName\": \"Mr.Server\"}";
    }

}
下面是JerseyClient代码

public class Program {
    public static void main(String[] args) throws Exception{

        String urlString="http://localhost:8080/MyWebService/webresources/myresource/sendReceiveJson";

        URL url=new URL(urlString);
        URLConnection connection=url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("{\"clientName\": \"Mr.Client\"}");
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
        }
        in.close();
}
}
但当我先运行服务,然后运行客户端时,我无法发送/接收JSON数据。我在
connection.getInputStream()
处遇到异常,这是

Server returned HTTP response code: 405 for URL: http://localhost:8080/hellointernet/webresources/myresource/sendReceiveJson
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)

请指导我,需要纠正什么,或者我是否走错了方向

资源方法被注释为@GET,这意味着任何输入数据都必须是查询字符串参数

在这个上下文中,@Consumes(MediaType.APPLICATION\u JSON)没有多大意义,因为GET只支持应用程序\u FORM\u URLENCODED

当客户端调用setDoOutput(true)时,它可能会将HTTP调用切换到POST,从而导致不允许使用405方法

如果你想使用JSON,你应该用@POST来更改@GET注释。如果你的客户电话真的是一个帖子,那么它应该会起作用。可以使用以下方法指定它:

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

这个API的级别非常低,所以我强烈建议您使用Jersey的客户端API。请看

您是否遇到某种异常?亲爱的,我刚刚看到客户端程序终止。