Consuming REST API with Java

后端 未结 2 1624
轻奢々
轻奢々 2021-01-13 03:25

I have a management web application located on a remote server. This app was written using a MEAN stack and I have a list of all the RESTful routes necessary to connect to t

相关标签:
2条回答
  • 2021-01-13 04:14

    There are plenty of libraries to consume REST applications in Java nowadays.

    The standard

    The JAX-RS Client API (javax.ws.rs.client package), defined in the JSR 339, is the standard way to consume REST web services in Java. Besides others, this specification is implemented by Jersey and RESTEasy.

    JAX-RS vendor specific proxy-based clients

    Both Jersey and RESTEasy APIs provide a proxy framework.

    The basic idea is you can attach the standard JAX-RS annotations to an interface, and then implement that interface by a resource class on the server side while reusing the same interface on the client side by dynamically generating an implementation of that using java.lang.reflect.Proxy calling the right low-level client API methods.

    For more details, check the following:

    • Jersey proxy-based client API
    • RESTEasy proxy-based client API

    Other resources

    There are a few other good options you may consider as alternative to the JAX-RS Client API:

    • Spring RestTemplate
    • OkHttp
    • Retrofit
    • Netflix Feign
    0 讨论(0)
  • 2021-01-13 04:20

    I would begin by reading the documentation for Jersey, specifically the Client portion. You will want to familiarize yourself with the WebTarget class and it is invoked (example from the documentation):

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(MyClientResponseFilter.class);
    clientConfig.register(new AnotherClientFilter());
    
    Client client = ClientBuilder.newClient(clientConfig);
    client.register(ThirdClientFilter.class);
    
    WebTarget webTarget = client.target("http://example.com/rest");
    webTarget.register(FilterForExampleCom.class);
    WebTarget resourceWebTarget = webTarget.path("resource");
    WebTarget helloworldWebTarget = resourceWebTarget.path("helloworld");
    WebTarget helloworldWebTargetWithQueryParam =
    helloworldWebTarget.queryParam("greeting", "Hi World!");
    
    Invocation.Builder invocationBuilder =
        helloworldWebTargetWithQueryParam.request(MediaType.TEXT_PLAIN_TYPE);
    invocationBuilder.header("some-header", "true");
    
    Response response = invocationBuilder.get();
    System.out.println(response.getStatus());
    System.out.println(response.readEntity(String.class));
    
    0 讨论(0)
提交回复
热议问题