rest - jersey-server、jersey-client、jersey-grizzly 在 RESTful 应用程序中的用途

标签 rest maven tomcat jersey jersey-client

我正在尝试使用 Maven、Apache Tomcat 7.0、Eclipse IDE 创建一个基本的 RESTful 应用程序。我在 google 提供的一些示例代码中遇到了 jersey-server、jersey-client、jersey-grizzly 等 maven 依赖项的使用。

我想知道这些依赖关系的目的,即。我们为什么要添加它们,它的作用是什么,它们是如何工作的?

我已经引用了几个 Jersey javadoc,但无法获得清晰的图片。请提供一个简单的解释。

提前致谢

最佳答案

简而言之:您使用 jersey-server 公开 REST API,如本例所示:

@Path("/hello")
class RESTDispatcher {

    @GET
    @Path("/world")
    public String helloWorld() {
        return "Hello world!"
    }
}

您使用 jersey-client 来使用 REST API

public static String callRestAPI(String[] args) {
    Invocation.Builder builder = ClientBuilder
                                .newClient()
                                .target("http://localhost/hello/world");
    Response response = builder.method("GET");
    String result = response.readEntity(String.class);
    return result; 
    //will return "Hello world!" with our previous example deployed on localhost
}

而 jersey-grizzly 只是为了将 jersey 与 grizzly 服务器一起使用。

更新
我的意思是每次需要调用别人暴露的REST API时,我们都需要jersey-client。
我的 jersey-client 使用示例假定第一个示例部署在您的本地主机上。请参阅第一个示例的注释,类的 @Path 和方法的 @Path 导致路径 /hello/world,应该使用 HTTP 调用GET 请求(参见 @GET 注释)。
所以我们用那个目标创建 REST 客户端

Invocation.Builder builder = ClientBuilder
                            .newClient()
                            .target("http://localhost/hello/world");

然后我们用 HTTP GET 请求调用这个目标

Response response = builder.method("GET");

然后我们知道(从 helloWorld 方法的签名)这个 API 响应包含一个可以反序列化为 String 实例的实体。所以我们把它读入“result”变量

String result = response.readEntity(String.class);

您应该将反序列化的目标类作为参数提供给响应的 readEntity 方法。
此外,REST API 仅返回字符串的情况并不常见。相反,它们返回 JSON 或 XML。 在那种情况下,您可以使用 JAXB 来读取实体,Jersey 与它完美配合。检查this part of documentation for XML supportthis for JSON .

关于rest - jersey-server、jersey-client、jersey-grizzly 在 RESTful 应用程序中的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213760/

相关文章:

java - 如何在 AWS EC2 自动缩放组中仅在一个 tomcat 实例中启动 Web 进程

php - 无法使用 WP REST API 2.0 插件通过基本身份验证进行身份验证

javascript - Ra-data-simple-rest 不工作 |错误 : total is not a number and newRecords. forEach 不是函数

rest - REST 适合 Web 应用程序吗?

java - Wicket + Tomcat安装中 "resources"上下文路径如何协同工作

tomcat - 在应用程序代码中使用 Tomcats 配置的执行器?

REST - 如何设计带有复合键的 URI?

java - 如何使用 Maven 部署多项目?

android - 连结 3 : Version clash for one artifact in two different repos of one group

java - RuntimeEnvironmentPropertiesConfigurer 问题 - 在 tomcat 上运行 Broadleaf 管理时