簡體   English   中英

REST服務URI映射到Java內部類

[英]Rest Service URI mapping to Java Inner Classes

我必須對其余的服務操作進行建模,在這些操作中,我試圖創建一個URI以打入Java內部類。 讓我知道是否可以使用Rest Web Service來實現? 我正在使用輕松的服務。

編輯:(使用peeskillet的答案提供的代碼)

javax.ws.rs.ProcessingException: Unable to invoke request
at  org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:287)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:407)

Caused by: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8081 refused
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:643)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:283)
... 26 more
Caused by: java.net.ConnectException: Connection refused

請告知資源類是否可以作為其他類的內部類

是的,這是可能的,但是我們不能簡單地對內部類路徑@Path注釋,並期望調用到達該位置。 我們需要使用“子資源定位器”。 基本上,它可以是僅使用@Path注釋的方法,該方法將返回內部資源類的實例。 就像是

@Path("/messages")
public class MessageResource {

    @GET
    @Path("/{id}")
    public Response getMessage(@PathParam("id") int id) {
        return Response.ok("messages, id: " + id).build();
    }

    @Path("/{id}/comments")
    public CommentsResource getComments() {
        return new CommentsResource();
    }

    public class CommentsResource {

        @GET
        @Path("/{id}")
        public Response getComment(@PathParam("id") int id) {
            return Response.ok("Hello Sub-Resource Locators").build();
        }
    }
}

我們可以測試一下

@Test
public void testResteasy() {
    WebTarget target = client.target(TestPortProvider.generateURL(BASE_URI))
            .path("messages").path("1234").path("comments").path("5678");
    Response response = target.request().get();
    System.out.println("Status:" + response.getStatus());
    System.out.println("Response: " + response.readEntity(String.class));
    response.close();
}

我們將得到響應Hello Sub-Resource Locators


進一步閱讀


編輯:

根據您提供的錯誤, TestPortProvider將使用端口8081,並使用http://localhost:8081開始URI。 您傳遞給gererateURL將被追加。 通常,我將其用於嵌入式服務器測試。 但是,如果您正在運行實際的服務器,則它很可能位於端口8080上。我建議僅傳遞String基本URL,例如:

WebTarget target = client.target("http://localhost:8080/MyApp/rest")
        .path("messages").path("1234").path("comments").path("5678");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM