简体   繁体   中英

Java server side annotated REST client library

I'm building a middleware service that consumes external REST services (from the server side). I'm currently using Spring boot with RestTemplate to make the remote calls.

    Map<String, String> urlVariables = new HashMap<>();
    urlVariables.put("address", IP);
    urlVariables.put("port", PORT);
    urlVariables.put("par1", parameter1);
    urlVariables.put("par2", parameter2);

    MyServiceResponse state =
            restTemplate.getForObject("http://{address}:{port}/service/{par1}/{par2}", MyServiceResponse.class, urlVariables);

I was wondering whether there's any library that provides annotations to automatically generate REST clients, like Volley does in Android.

@GET(url="http://{address}:{port}/service/{par1}/{par2}")
public MyServiceResponse getCurrentState(String address, String port, String par1, String par2)

There is the RESTEasy Proxy Framework :

Resteasy has a client proxy framework that allows you to use JAX-RS annotations to invoke on a remote HTTP resource. The way it works is that you write a Java interface and use JAX-RS annotations on methods and the interface.

Are you looking for something like this?:

https://github.com/dpalmisano/NoTube-Beancounter-2.0/blob/master/platform/src/main/java/io/beancounter/platform/rai/MyRaiTVService.java#L45

@POST
@Path("/login/auth")
public Response loginWithAuth(
        @FormParam("username") String username,
        @FormParam("token") String token

) {
    try {
        Validations.checkNotEmpty(username, "Missing username parameter");
        Validations.checkNotEmpty(token, "Missing MyRaiTV token parameter");
    } catch (Exception ex) {
        return error(ex.getMessage());
    }

You can use REST Gap for this. You only need to:

  • Have Spring MVC or JAX-RS style annotated interfaces
  • Call the REST Gap factory and pass your interface and a RestTemplate instance
  • Receive an implementation of your interface that calls your REST Service

This is how it looks in code (for a Spring-MVC interface IPetStoreService):

// Create client
IPetStoreService client = RESTTemplateSpringMVCFactory
    .create(restTemplate, "http://mypetstore.com/rest", IPetStoreService.class);

// Call it!
List<Pet> pets = client.listPets();

That's it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM