Skip to content Skip to sidebar Skip to footer

Why Is Retrofit Adding A Trailing Slash To All Urls?

Editing question with more details : I understand the use of service interfaces in Retrofit. I want to make a call to a URL like this : http://a.com/b/c (and later append query pa

Solution 1:

You're expected to pass the base URL to the setEndpoint(...) and define /repos/... in your service interface.

A quick demo:

classContributor {

    Stringlogin;

    @OverridepublicStringtoString() {
        returnString.format("{login='%s'}", this.login);
    }
}

interfaceGitHubService {

    @GET("/repos/{organization}/{repository}/contributors")
    List<Contributor> getContributors(@Path("organization") String organization,
                                      @Path("repository") String repository);
}

and then in your code, you do:

GitHubService service = new RestAdapter.Builder()
        .setEndpoint("https://api.github.com")
        .build()
        .create(GitHubService.class);

List<Contributor> contributors = service.getContributors("square", "retrofit");
System.out.println(contributors);

which will print:

[{login='JakeWharton'}, {login='pforhan'}, {login='edenman'}, {login='eburke'}, {login='swankjesse'}, {login='dnkoutso'}, {login='loganj'}, {login='rcdickerson'}, {login='rjrjr'}, {login='kryali'}, {login='holmes'}, {login='adriancole'}, {login='swanson'}, {login='crazybob'}, {login='danrice-square'}, {login='Turbo87'}, {login='ransombriggs'}, {login='jjNford'}, {login='icastell'}, {login='codebutler'}, {login='koalahamlet'}, {login='austynmahoney'}, {login='mironov-nsk'}, {login='kaiwaldron'}, {login='matthewmichihara'}, {login='nbauernfeind'}, {login='hongrich'}, {login='thuss'}, {login='xian'}, {login='jacobtabak'}]

Can we have variable parameters (non final) being passed to Retrofit @GET or @POST annotations ?

No, values inside (Java) annotations must be declared final. However, you can define variable paths, as I showed in the demo.

EDIT:

Note Jake's remark in the comments:

Worth noting, the code linked in the original question deals with the case when you pass https://api.github.com/ (note the trailing slash) and it gets joined to /repos/... (note the leading slash). Retrofit forces leading slashes on the relative URL annotation parameters so it de-dupes if there's a trailing slash on the API url.

Post a Comment for "Why Is Retrofit Adding A Trailing Slash To All Urls?"