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

标签 java web-services rest jersey jersey-client

我是 Jersey 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_JSON) 没有多大意义,因为通过 GET 仅支持 APPLICATION_FORM_URLENCODED。

当您的客户端调用 setDoOutput(true) 时,它可能会将您的 HTTP 调用切换为 POST,从而导致 405 Method Not Allowed。

如果您想使用 JSON,您应该将 @GET 注释改为 @POST。如果确实是 POST,那么您的客户电话应该可以工作。您可以使用以下方法指定它:

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

虽然这个 API 级别很低,所以我强烈建议您改用 Jersey 的客户端 API。参见 https://jersey.java.net/documentation/1.17/client-api.html

关于java - 在 Jersey Java 中向 REST WebService 发送和接收 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19050628/

相关文章:

c# - Web service call slow from dev 解决方案

java - RESTful WebService 消费XML,如何调用?

java - Eclipse 中的 java 中未定义构造函数,尽管已定义

java - 查找二维数组中两个对象之间的距离,而不是对角线

java - Google API v3 通过传递文件夹名称检查存在的文件夹

javascript - 如何在以ajax方式插入后刷新我的服务器控件?

java - 替换特定数字 - For 循环

java - Apache Axis2 的 Eclipse 插件来创建 web 服务

php - 无法为 float 金额创建 Paypal 付款

java - Jersey 资源 .class 加载