美文网首页
Retrofit 2 运行时改变BaseUrl

Retrofit 2 运行时改变BaseUrl

作者: 河婆墟邓紫棋 | 来源:发表于2016-11-19 23:54 被阅读6079次

多API下的调试,如果每次都改变API然后去重新打包.apk,会比较痛苦,在调试过程中,如果要进行验证API是否成功,可以在运行时改变API达到运行一次验证各API。栗子API采用聚合数据(历史上的今天)(微信精选)

/*
 * Serice生成器
 */
public class ServiceGenerator {

    private static String BASE_URL = "http://api.juheapi.com/";

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL);

    public static <T> T createServiceFrom(Class<T> serviceClass) {
        return builder.build().create(serviceClass);
    }
}

在上述类中,加入改变BASE_URL的操作:

public static void changeApiBaseUrl(String newApiBaseUrl) {
    BASE_URL = newApiBaseUrl;

    builder = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL);
}

调用栗子:

public void getToh(String key, String version, String month, String day, Callback<Toh> callBack) {
    mWeChatQuery = ServiceGenerator.createServiceFrom(WeChatQueryService.class);
    Call<Toh> call = mWeChatQuery.getToh(key,version,month, day);
    call.enqueue(callBack);
}

public void getWeChatQuery(String key, Callback<WeChatQuery> callback) {
    ServiceGenerator.changeApiBaseUrl(ApiAddressPool.API_JUHE_WECHAT);//改变API
    mWeChatQuery = ServiceGenerator.createServiceFrom(WeChatQueryService.class);
    Call<WeChatQuery> call = mWeChatQuery.getWeChatQuery(key, "", "", "");
    call.enqueue(callback);
}

运行后结果:(输出的两次BaseUrl)

I/System.out: http://api.juheapi.com/
I/System.out: http://v.juhe.cn/

总结:
好像没有什么卵用...也有可能我没理解Retrofit 2 — How to Change API Base Url at Runtime 的原意..

相关文章

网友评论

      本文标题:Retrofit 2 运行时改变BaseUrl

      本文链接:https://www.haomeiwen.com/subject/wsbepttx.html