Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

java - Using absolute URLs with Retrofit

I have a HAL API that I'm working with and in many cases I need to send request (with different methods) to a URL that I get back from API. Meaning I don't want to hardcode the path of URL in my retrofit api interface but what I want is just sending a simple request using retrofit to that URL. I'm using Volley now and I know that I can use OkHttp for this purpose but I was wondering if there is a nice way of doing such thing in Retrofit?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Recently Square has released the Retrofit v2.0.0 BETA and it has a built-in support for dynamic URLs. Even though the Library is in Beta, based on what Jake Wharton told us in DroidCon NYC 2015, all the apis are stable and will not change. I'm personally adding it to my production so its up to you.

You will find the following links useful if you decide to do the upgrade:
Jake Wharton presentation @ DroidCon NYC 2015
A very good guide on the changes

In simple word, you can now use the api annotations (like @GET or @POST and others) without any path and then you pass in a @URL to your api method that the method will use to call.

----------------Retrofit 1.x

I figured out a nice way for doing this and would like to share it.

The trick is to use the dynamic URL as your End Point in the creation of RestAdapter and then have a empty path on your API interface.

Here is how I did it:

public RestAdapter getHostAdapter(String baseHost){
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(baseHost)
            .setRequestInterceptor(requestInterceptor)
            .build();

    return restAdapter;
}

I build my restAdapter using this method and then I have this in my interface:
(this will not work if your URL has query parameters added to it. See next answer for solution to that case)

public interface General {
    @GET("/")
    void getSomething(Callback<SomeObject> callback);
}

and finally using them like this:

getHostAdapter("YOUR_DYNAMIC_URL").create(General.class)
    .getSomething(new Callback<SomeObject>(){
        ...
    })

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...