Android:如何使用翻新功能在所有url的末尾添加内容?

时间:2019-04-25 17:42:45

标签: android timestamp retrofit2

我将改造用于Web服务。我想将时间戳添加到所有请求网址。我可以这样吗?

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API.BASE_URL + Constants.TimeStamp + System.currentTimeMillis() + Constants.Slash)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

3 个答案:

答案 0 :(得分:0)

我的情况是,您应按以下方式使用。如果要检查此链接enter link description here

Mockito.when(client.handleRequest(request)).thenReturn(new OnlineResponse());

答案 1 :(得分:0)

您可以这样做:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user, @Query("timestamp") long timestamp);
}

答案 2 :(得分:0)

您的实现将向改造实例执行的所有请求添加相同的初始时间戳。这就是你想要的吗?

如果要将当前/最新时间戳记作为每次调用中url路径的一部分,请使用拦截器:

 val okHttpClient = OkHttpClient.Builder()
            .addInterceptor( object : Interceptor {
                override fun intercept(chain: Interceptor.Chain): Response {
                    val originalRequest = chain.request()
                    val originalHttpUrl = originalRequest.url()

                    val timestampUrl = originalHttpUrl.newBuilder()
                            .addPathSegment(System.currentTimeMillis().toString())
                            .build()

                    val requestBuilder = originalRequest.newBuilder()
                            .url(timestampUrl)
                    return chain.proceed(requestBuilder.build())
                }
            })
            .build()

val retrofit = Retrofit.Builder()
        .baseUrl(API.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()

如果您要将时间戳作为查询参数传递(如Yevhenii建议的那样),则将拦截器替换为:

            object : Interceptor {
                override fun intercept(chain: Interceptor.Chain): Response {
                    val originalRequest = chain.request()
                    val originalHttpUrl = originalRequest.url()

                    val timestampUrl = originalHttpUrl.newBuilder()
                            .addQueryParameter("timestamp", System.currentTimeMillis().toString())
                            .build()

                    val requestBuilder = originalRequest.newBuilder()
                            .url(timestampUrl)
                    return chain.proceed(requestBuilder.build())
                }
            }