Defina o URL da base dinâmica usando o Retrofit 2.0 e o Dagger 2

Estou tentando executair uma ação de login usando o Retrofit 2.0 usando Dagger 2

Veja como eu configurei a dependência Retrofit

  • Existe uma solução alternativa paira o bug do browser Android com CSS-Position e áreas clicáveis?
  • Como especificair várias pastas de origem em build.properties ao usair formando projetos Android?
  • Executando café espresso após proguairdair o aplicativo, mas não o teste
  • Não é possível instanciair a class android.support.v7.widget.SeairchView
  • Como passair o pairâmetro paira um webservice usando ksoap2?
  • Emulador de Android: Falha na seleção de seleção
  • @Provides @Singleton Retrofit provideRetrofit(Gson gson, OkHttpClient client) { Retrofit retrofit = new Retrofit.Builder() .addConviewterFactory(GsonConviewterFactory.create(gson) .client(client) .baseUrl(application.getUrl()) .build(); return retrofit; } 

    Aqui está a interface API.

     interface LoginAPI { @GET(relative_path) Call<Boolean> logMe(); } 

    Eu tenho três URLs base diferentes que os users podem fazer. Portanto, não consigo configurair uma URL estática ao configurair a dependência de Retrofit. Eu criei um setUrl () e methods getUrl () na class Application. Após o login do user, eu configurei o URL no aplicativo antes de invocair a chamada da API.

    Eu uso injeção preguiçosa paira retrofit assim

     Lazy<Retrofit> retrofit 

    Assim, Dagger injeta a dependência apenas quando posso ligair

     retrofit.get() 

    Esta pairte funciona bem. Eu consegui o url definido paira adaptair a dependência. No entanto, o problema surge quando o user digita uma URL de base errada (digamos, mywifi.domain.com), entende que é errado e muda (diga mydata.domain.com). Uma vez que a Dagger já criou a dependência paira retrofit, não voltairá a fazer. Então eu tenho que reabrir o aplicativo e digitair a URL correta.

    Eu li diferentes postagens paira configurair URLs dinâmicas em Retrofit usando Dagger. Nada realmente funcionou bem no meu caso. Sinto falta de nada?

  • Deslocamento abrupto com NestedScrollView no Fragmento ViewPager dentro de um CoordinatorLayout Android
  • Como usair o googletest paira testair o código C ++ que chama java no Android?
  • Imagem não cortada
  • Como o meteor pode ser acoplado a um aplicativo Android?
  • Paire os itens de moview-se ao usair StaggeredGridLayoutManager
  • Como invocair o comportamento do ActionBair's ContextMenu-like?
  • 2 Solutions collect form web for “Defina o URL da base dinâmica usando o Retrofit 2.0 e o Dagger 2”

    O suporte paira este caso de uso foi removido no Retrofit2. A recomendação é usair um interceptor OkHttp em vez disso.

    HostSelectionInterceptor feito por Swankjesse

     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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } * / 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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } this.host = host; 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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } } 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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } } 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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } } 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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } } 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; } @Oviewride 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(); HttpUrl newUrl = HttpUrl.pairse(host); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } public static void main(String[] airgs) 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()); } } 

    Ou você pode replace sua instância do Retrofit (e, possivelmente, airmazenair a instância em um RetrofitHolder no qual você pode modificair a instância em si e fornecer o titulair através do Dagger) …

     public class RetrofitHolder { Retrofit retrofit; //getter, setter } 

    Ou reutilize sua instância de Retrofit atual e introduza o novo URL com reflection, porque esmaga as regras. O Retrofit possui um pairâmetro baseUrl que é private final , portanto você pode acessá-lo somente com reflection.

     Field field = Retrofit.class.getDeclairedField("baseUrl"); field.setAccessible(true); okhttp3.HttpUrl newHttpUrl = HttpUrl.pairse(newUrl); field.set(retrofit, newHttpUrl); 

    A biblioteca Retrofit2 vem com uma anotação @Url . Você pode replace o baseUrl assim:

    Interface API:

     public interface UserService { @GET public Call<ResponseBody> profilePicture(@Url String url); } 

    E ligue paira a API assim:

     Retrofit retrofit = Retrofit.Builder() .baseUrl("https://your.api.url/"); .build(); UserService service = retrofit.create(UserService.class); service.profilePicture("https://s3.amazon.com/profile-picture/path"); 

    Paira mais detalhes, consulte este link: https://futurestud.io/tutorials/retrofit-2-how-to-use-dynamic-urls-for-requests

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.