改造2 - 动态URL

pde*_*d59 153 android retrofit

使用Retrofit 2,您可以在服务方法的注释中设置完整的URL,如:

public interface APIService {
  @GET("http://api.mysite.com/user/list")
  Call<Users> getUsers();
}
Run Code Online (Sandbox Code Playgroud)

但是,在我的应用程序中,我的webservices的URL在编译时是未知的,应用程序在下载的文件中检索它们,所以我想知道如何使用Retrofit 2和完整的动态URL.

我试图设置一个完整的路径,如:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path("fullUrl") fullUrl);
}

new Retrofit.Builder()
  .baseUrl("http://api.mysite.com/")
  .build()
  .create(APIService.class)
  .getUsers("http://api.mysite.com/user/list"); // this url should be dynamic
  .execute();
Run Code Online (Sandbox Code Playgroud)

但在这里,Retrofit并未发现该路径实际上是一个完整的URL并且正在尝试下载 http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist

有关如何使用这种动态网址进行Retrofit的任何提示吗?

谢谢

Yaz*_*llo 336

我认为你是以错误的方式使用它.以下是更改日志的摘录:

新增:@Url参数注释允许传递端点的完整URL.

所以你的界面应该是这样的:

public interface APIService {
    @GET
    Call<Users> getUsers(@Url String url);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我使用这个@Url注释.然后我们应该写什么.baseUrl()?? (10认同)
  • 你应该写你的主要网址.@Url参数无论如何都会覆盖它. (10认同)
  • 我尝试添加上面的URL,但我通常为改装构建器设置的baseUrl覆盖了我在参数中指定的完整URL,因此它不是http://dynamic.com而是转换为http:// MyBaseUrl /http://dynamic.com (4认同)
  • 为什么要使用baseurl虽然端点的url是完整的? (2认同)

And*_*czl 104

我想只替换url的一部分,使用这个解决方案,我不必传递整个url,只需要动态部分:

public interface APIService {

  @GET("users/{user_id}/playlists")
  Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}
Run Code Online (Sandbox Code Playgroud)


fgy*_*ica 29

您可以在注释上使用编码标志@Path:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
Run Code Online (Sandbox Code Playgroud)
  • 这将防止更换/%2F.
  • 但是,它不会使您免于?被替换%3F,因此您仍然无法传递动态查询字符串.

  • 是'编码'一个错字?我只能使用'encode'. (3认同)
  • 以及如何替换 %3F ? (2认同)

小智 18

从Retrofit 2.0.0-beta2开始,如果您有来自此URL的服务响应JSON: http:// myhost/mypath

以下不起作用:

public interface ClientService {
    @GET("")
    Call<List<Client>> getClientList();
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList().execute();
Run Code Online (Sandbox Code Playgroud)

但这没关系:

public interface ClientService {
    @GET
    Call<List<Client>> getClientList(@Url String anEmptyString);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList("").execute();
Run Code Online (Sandbox Code Playgroud)


小智 15

你可以使用这个:

@GET("group/{id}/users")

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

有关更多信息,请参阅文档https://square.github.io/retrofit/


Vin*_*ode 8

Retrofit (MVVM) 中使用 Get 和 Post 方法的动态 URL

改造服务接口:

public interface NetworkAPIServices {

@POST()
Observable<JsonElement> executXYZServiceAPI(@Url String url,@Body AuthTokenRequestModel param);


@GET
Observable<JsonElement> executeInserInfo(@Url String url);
Run Code Online (Sandbox Code Playgroud)

MVVM 服务类:

   public Observable<JsonElement> executXYZServiceAPI(ModelObject object) {
    return networkAPIServices.authenticateAPI("url",
            object);
}

 public Observable<JsonElement> executeInserInfo(String ID) {
    return networkAPIServices.getBank(DynamicAPIPath.mergeUrlPath("url"+ID)));
}
Run Code Online (Sandbox Code Playgroud)

和改造客户端类

 @Provides
@Singleton
@Inject
@Named("provideRetrofit2")
Retrofit provideRetrofit(@Named("provideRetrofit2") Gson gson, @Named("provideRetrofit2") OkHttpClient okHttpClient) {


   builder = new Retrofit.Builder();
    if (BaseApplication.getInstance().getApplicationMode() == ApplicationMode.DEVELOPMENT) {
        builder.baseUrl(NetworkURLs.BASE_URL_UAT);
    } else {
        builder.baseUrl(NetworkURLs.BASE_URL_PRODUCTION);
    }


    builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    builder.client(okHttpClient);
    builder.addConverterFactory(GsonConverterFactory.create(gson));


    return builder.build();
}
Run Code Online (Sandbox Code Playgroud)

例如这是网址:https : //gethelp.wildapricot.com/en/articles/549-changed-your

baseURL : https://gethelp.wildapricot.com

剩下的@Url:/en/articles/549-changed-your(这是你在复古服务类中传递的)


小智 5

第1步

  Please define a method in Api interface like:-
 @FormUrlEncoded
 @POST()
 Call<RootLoginModel> getForgotPassword(
        @Url String apiname,
        @Field(ParameterConstants.email_id) String username
 );
Run Code Online (Sandbox Code Playgroud)

步骤 2 对于最佳实践,为改造实例定义一个类:-

  public class ApiRequest {
       static Retrofit retrofit = null;



public static Retrofit getClient() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
            .addInterceptor(logging)
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .build();

    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(URLConstants.base_url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
Run Code Online (Sandbox Code Playgroud)

} 步骤3中 定义的活动: -

  final APIService request =ApiRequest.getClient().create(APIService.class);
  Call<RootLoginModel> call = request.getForgotPassword("dynamic api 
  name",strEmailid);
Run Code Online (Sandbox Code Playgroud)


Moj*_*ghi 5

用 kotlin 编写的RetrofitHelper库将允许您使用几行代码进行 API 调用,并且您可以在每次调用中使用不同的 URL、 headers 和 Params

在您的应用程序类中添加多个 URL,如下所示:

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                // api url
                .setBaseUrl("https://reqres.in/")
                // you can set multiple urls
                // .setUrl("example","http://ngrok.io/api/")
                // set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                // enable cache
                .enableCaching(this)
                // add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  
Run Code Online (Sandbox Code Playgroud)

然后在调用中使用您需要的 URL:

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                // api url
                .setBaseUrl("https://reqres.in/")
                // you can set multiple urls
                // .setUrl("example","http://ngrok.io/api/")
                // set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                // enable cache
                .enableCaching(this)
                // add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档