4.8. MicroProfile REST 客户端开发
MicroProfile REST 客户端启用分布式对象通信版本,它也在 CORBA、Java 远程方法调用(RMI)、JBoss 远程方法传递项目和 RESTEasy 中实施。例如,考虑资源:
@Path("resource")
public class TestResource {
@Path("test")
@GET
String test() {
return "test";
}
}
以下示例演示了如何使用 Jakarta RESTful Web Services-native 来访问 TestResource 类:
Client client = ClientBuilder.newClient();
String response = client.target("http://localhost:8081/test").request().get(String.class);
但是,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();
在前面的示例中,让 TestResource 类的调用 在使用 类时变得更容易,如调用 TestResource Intfservice.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);
}
调用 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