使用改进不同的域

时间:2016-12-09 06:48:00

标签: android retrofit endpoint

我使用改造库进行Android网络操作。我有两个域名地址。我用SharedPreferences存储地址。我如何使用不同的端点。

例如:

www.mehmet.com/api/list
ww.deniz.com/api/list
万维网......
WWW .....

代码:

public class ptsApi {

    public static String BASE_URL = "";
    private static ptsApi instance;
    private ptsService ptsService;

    private ptsApi(Context c) {
        SharedPreferences sharedpreferences =  c.getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        String BASE_URL = sharedpreferences.getString("api","").toString();

        final Gson gson =
                new GsonBuilder().
                        setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                        .create();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        ptsService = retrofit.create(ptsService.class);
    }

    public static ptsApi getInstance(Context c) {
        if (instance == null) {
            instance = new ptsApi(c);
        }
        return instance;
    }


    public Observable<SearchModel> getSearch(@NonNull String plate) {
        return ptsService.searchData(plate);
    }

4 个答案:

答案 0 :(得分:1)

使用类似

的内容
public void getRetrofit(Sting baseDomain){
         Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseDomain)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
   return retorfit;
}

你可以更改域并创建一个新的retroift实例并相应地使用它来进行api调用

在你的代码中你可以像上面一样传递域和上下文。

答案 1 :(得分:1)

你可以试试这个。

public class ptsApi {
    enum TYPE {
        MEHMENT, DENIZ

    }

    private static ptsApi instance;
    private ptsService ptsService;

    private ptsApi(Context c, TYPE type) {
        final String BASE_URL = getEndpoint(type);

        final Gson gson =
                new GsonBuilder().
                        setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                        .create();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        ptsService = retrofit.create(ptsService.class);
    }

    public static ptsApi getInstance(Context c, TYPE type) {
        if (instance == null) {
            instance = new ptsApi(c, type);
        }
        return instance;
    }


    public Observable<SearchModel> getSearch(@NonNull String plate) {
        return ptsService.searchData(plate);
    }

    public String getEndpoint(TYPE type) {
        SharedPreferences sharedpreferences = c.getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        switch (type) {
            case MEHMENT:
                return sharedpreferences.getString("mehmentApi","").toString();
            case DENIZ:
                return sharedpreferences.getString("denizApi","").toString();
            default:
                return "your default";
        }
    }
}

或者您可以创建一些方法,如

public static ptsApi getMehmetInstance(Context c) {
    if (instance == null) {
        instance = new ptsApi(c, MEHMENT);
    }
    return instance;
}
public static ptsApi getDenizInstance(Context c) {
    if (instance == null) {
        instance = new ptsApi(c, DENIZ);
    }
    return instance;
}

答案 2 :(得分:0)

这个怎么样?有一个方法可以在更改baseUrl时更新ptsService实例

public class ptsApi {

    public static String BASE_URL = "";
    private static ptsApi instance;
    private ptsService ptsService;

    // a function you can call to change the base url
    // which in turn updates the ptsService instance
    // to start making calls to the new baseUrl.
    public void changeBaseUrl(String newBaseUrl) {
        BASE_URL = newBaseUrl;
        updatePtsService();
    }

    // Created this function to remove code duplication
    private void updatePtsService() {
        final Gson gson =
                new GsonBuilder().
                        setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                        .create();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        ptsService = retrofit.create(ptsService.class);
    }

    private ptsApi(Context c) {
        SharedPreferences sharedpreferences =  c.getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        String BASE_URL = sharedpreferences.getString("api","").toString();
        // re-using this to remove code duplication.
        updatePtsService();
    }

    public static ptsApi getInstance(Context c) {
        if (instance == null) {
            instance = new ptsApi(c);
        }
        return instance;
    }


    public Observable<SearchModel> getSearch(@NonNull String plate) {
        return ptsService.searchData(plate);
    }
}

答案 3 :(得分:0)

您可以使用一个带有okhttp拦截器的Retrofit实例,该实例允许对URL主机名进行运行时更改:

import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/** An interceptor that allows runtime changes to the URL hostname. */
public final class HostSelectionInterceptor implements Interceptor {
  private volatile String host;

  public void setHost(String host) {
    this.host = host;
  }

  @Override public okhttp3.Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String host = this.host;
    if (host != null) {
      HttpUrl newUrl = request.url().newBuilder()
          .host(host)
          .build();
      request = request.newBuilder()
          .url(newUrl)
          .build();
    }
    return chain.proceed(request);
  }

  public static void main(String[] args) throws Exception {
    HostSelectionInterceptor interceptor = new HostSelectionInterceptor();

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .build();

    Request request = new Request.Builder()
        .url("http://www.coca-cola.com/robots.txt")
        .build();

    okhttp3.Call call1 = okHttpClient.newCall(request);
    okhttp3.Response response1 = call1.execute();
    System.out.println("RESPONSE FROM: " + response1.request().url());
    System.out.println(response1.body().string());

    interceptor.setHost("www.pepsi.com");

    okhttp3.Call call2 = okHttpClient.newCall(request);
    okhttp3.Response response2 = call2.execute();
    System.out.println("RESPONSE FROM: " + response2.request().url());
    System.out.println(response2.body().string());
  }
}

获取更多信息:

  1. https://gist.github.com/swankjesse/8571a8207a5815cca1fb

  2. https://github.com/square/retrofit/issues/1404#issuecomment-207408548