Retrofit解决使用多个BASE_URL的问题

    private static RetrofitManager mRetrofitManager;
    private static String BASE_URL="http://www.zhaoapi.cn/";
    private final BaseApis mBaseApis;

    private RetrofitManager() {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(5000,TimeUnit.MILLISECONDS)
                .connectTimeout(5000,TimeUnit.MILLISECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .build();

         mBaseApis = retrofit.create(BaseApis.class);

    }

添加以下方法

public void setBaseUrl(String baseUrl){
        BASE_URL=baseUrl;
}

调用时

public class IModelImpl implements IModel{
    @Override
    public void requestData(String url, Map map, final Class clazz, int type, final MyCallBack myCallBack) {

        if (type==0){
            RetrofitManager.getInstance().setBaseUrl("http://www.my.cn/"); //设置要用的URL

            RetrofitManager.getInstance().get(url, new RetrofitManager.HttpListener() {
                @Override
                public void onFail() {

                }

                @Override
                public void onResponse(String json) {

                    Object o = new Gson().fromJson(json, clazz);
                    myCallBack.setData(o);
                }
            });

        }else if (type==1){
            RetrofitManager.getInstance().post(url,map, new RetrofitManager.HttpListener() {
                @Override
                public void onFail() {

                }

                @Override
                public void onResponse(String json) {

                    Object o = new Gson().fromJson(json, clazz);
                    myCallBack.setData(o);
                }
            });
        }

    }
}

也就是要用那个BASE_URL,就传那个

你可能感兴趣的:(Retrofit解决使用多个BASE_URL的问题)