4.8. MicroProfile REST 客户端开发


MicroProfile REST 客户端启用分布式对象通信版本,它也在 CORBA、Java 远程方法调用(RMI)、JBoss 远程方法传递项目和 RESTEasy 中实施。例如,考虑资源:

@Path("resource")
public class TestResource {
   @Path("test")
   @GET
   String test() {
      return "test";
   }
 }
Copy to Clipboard Toggle word wrap

以下示例演示了如何使用 Jakarta RESTful Web Services-native 来访问 TestResource 类:

Client client = ClientBuilder.newClient();
String response = client.target("http://localhost:8081/test").request().get(String.class);
Copy to Clipboard Toggle word wrap

但是,Microprofile REST 客户端通过直接调用 test()方法来支持 更直观的语法,如下例所示:

@Path("resource")
public interface TestResourceIntf {
    @Path("test")
    @GET
    public String test();
}

TestResourceIntf service = RestClientBuilder.newBuilder()
                              .baseUrl(http://localhost:8081/))
                              .build(TestResourceIntf.class);
String s = service.test();
Copy to Clipboard Toggle word wrap

在前面的示例中,让 TestResource 类的调用 在使用 TestResource Intf 类时变得更容易,如调用 service.test() 所示。

以下示例是 TestResourceIntf 类的更详细版本:

@Path("resource")
public interface TestResourceIntf2 {
   @Path("test/{path}")
   @Consumes("text/plain")
   @Produces("text/html")
   @POST
   public String test(@PathParam("path") String path, @QueryParam("query") String query, String entity);
}
Copy to Clipboard Toggle word wrap

调用 service.test("p", "q", "e") 方法会产生 HTTP 信息,如下例所示:

POST /resource/test/p/?query=q HTTP/1.1
Accept: text/html
Content-Type: text/plain
Content-Length: 1

e
Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat