【问题标题】:Retrofit removes query parameters from base urlRetrofit 从基本 url 中删除查询参数
【发布时间】:2019-04-25 12:43:49
【问题描述】:

我有用于所有请求的查询参数。它被添加到基本 url 如下

private val baseUrl = HttpUrl.Builder()
            .scheme("http")
            .host("ws.audioscrobbler.com")
            .addPathSegment("2.0")
            .addPathSegment("")
            .addQueryParameter("format", "json")
            .addQueryParameter("api_key", "val")
            .build()

retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .build()

api服务调用是

 @GET("./")
    fun searchTracks(@Query("otherParam") query: String): Call<Any>

在进行实际调用之前,该 URL 已正确构建。它删除了在基本 url 中添加的查询参数,只保留了在服务调用中添加的参数。
在调试中显示直到在ExecutorCallAdapterFactory 中调用delegate.enqueue():"http://ws.audioscrobbler.com/2.0/?format=json&api_key=val&otherParam=val"
显示在日志中(通过拦截器):“http://ws.audioscrobbler.com/2.0/?otherParam=val

知道为什么会发生这种情况以及如何保留参数吗?

【问题讨论】:

    标签: android retrofit retrofit2


    【解决方案1】:

    你应该在请求拦截器的url中添加查询参数。

            OkHttpClient.Builder httpClient =  
        new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {  
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            HttpUrl originalHttpUrl = original.url();
    
            HttpUrl url = originalHttpUrl.newBuilder()
                    .addQueryParameter("format", "json")
                    .addQueryParameter("api_key", "val")
                    .build();
    
            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .url(url);
    
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 2017-11-22
      • 2018-01-16
      • 2015-11-27
      • 1970-01-01
      • 2013-10-21
      相关资源
      最近更新 更多