Retrofit 1.6: Call RestService with various (TCP) ports

I need to contact the following four RESTS services.

Germany (Default): http://url.com/suggest?query=
Austria http://url.com:82/suggest?query=
Swiss: http://url.com:83/suggest?query=
Spain: http://url.com:84/suggest?query=

Basically, I have to call the same RESTS service for different TCP ports for each country. When I create a Retrofit-RestAdapter, I have to provide the endpoint (base-url):

RestAdapter.Builder builder = new RestAdapter.Builder();
    ObjectMapper mapper = new ObjectMapper();
    builder.setEndpoint("http://url.com");

If I want to access these four RESTS services mentioned above, do I need to create a RestAdapter for each of them? Or can you use only one instance of RestAdapter?

I tried to solve the problem by adding a TCP port as part of the RestInterface annotation, but this does not work:

public interface AutoSuggestRemote {
    @GET (":{port}/suggest")
    public Response getSuggestions(@Path ("port") Integer httpPort, @Query ("query") String query);
}

The following exception appears in Logcat:

java.lang.IllegalArgumentException: AutoSuggestRemote.getSuggestions: URL path ":{port}/suggest" must start with '/'.
        at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:123)
        at retrofit.RestMethodInfo.parsePath(RestMethodInfo.java:212)
        at retrofit.RestMethodInfo.parseMethodAnnotations(RestMethodInfo.java:165)
        at retrofit.RestMethodInfo.init(RestMethodInfo.java:133)
        at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:294)
        at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
        at $Proxy3.getSuggestions(Native Method)

So my question is if I need to create a RestAdapter instance for each RESTService, or is there a way to communicate with all four services using the same RestAdapter instance.

+4
1

Retrofit EndPoint , . @JakeWharton Dynamic Paths in Retrofit, EndPoint .

, @JakeWharton, .

public final class FooEndpoint implements Endpoint {
  private static final String BASE = "http://192.168.1.64:";

  private String url;

  public void setPort(String port) {
    url = BASE + port;
  }

  @Override public String getName() {
    return "default";
  }

  @Override public String getUrl() {
    if (url == null) throw new IllegalStateException("port not set.");
    return url;
  }
}

FooEndPoint . , .

FooEndPoint endPoint = new FooEndPoint();
endPoint.setPort(loadPortFromSomeWhere());

RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setEndpoint(endPoint);

RestAdapter .

+1

Source: https://habr.com/ru/post/1546151/


All Articles