Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit Override Endpoint

Tags:

java

retrofit

Can I override the endpoint path set on the RestAdapter builder? So say I have 20 endpoints that use the same base URL, but there is 1 that does not. I would like to call setEndpoint for all 20 to use, but override in the one case where I need to use a different base URL.

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

Use Endpoint path set on the builder:

 @GET("/relative
 Something getClip();

Use absolute path (doesn't work):

 @GET("http://absolute/path")
 Something getAlert();
like image 377
Steve Avatar asked Aug 26 '14 00:08

Steve


1 Answers

The RestAdapter will actually consult the EndPoint every time a request is made. This means that you can implement your own and pass it in the RestAdapter. Keeping a reference to it means that you'd be able to make change the url when you need.

public final class FooEndpoint implements Endpoint {
  private String url;

  public void setUrl(String url) {
    this.url = url;
  }

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

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

Then simply do something like so

FooEndPoint endPoint = new FooEndPoint();
// Keep a reference to this instance
endPoint.setUrl("url1");

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

SomeApi api = builder.build().create(SomeApi.class);
api.getSomeDataFromUrl1();

// when needed you can update the url
endPoint.setUrl("url2");

api.getSomeDataFromUrl2();
like image 178
Miguel Avatar answered Sep 26 '22 10:09

Miguel