【问题标题】:Add arguments to the end of a url in Retrofit在 Retrofit 中将参数添加到 url 的末尾
【发布时间】:2014-04-12 04:22:17
【问题描述】:

所以,我正在尝试发出如下所示的 REST 请求:https://api.digitalocean.com/droplets/?client_id=[client_id]&api_key=[api_key]

https://api.digitalocean.com 是端点,@GET("/droplets/") 是注解。我希望自动添加结束位,因为它对于我发出的任何 API 请求都是相同的,并且将它添加到每个请求中会很麻烦。有什么办法吗?

【问题讨论】:

    标签: java rest retrofit


    【解决方案1】:

    这是我的 Retrofit 2 拦截器:

        private static class AuthInterceptor implements Interceptor {
    
        private String mApiKey;
    
        public AuthInterceptor(String apiKey) {
            mApiKey = apiKey;
        }
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request().httpUrl()
                    .newBuilder()
                    .addQueryParameter("api_key", mApiKey)
                    .build();
            Request request = chain.request().newBuilder().url(url).build();
            return chain.proceed(request);
        }
    }
    

    【讨论】:

    • url() 而不是 okhttp3 中的 httpUrl()
    【解决方案2】:

    RequestInterceptor 实例传递给添加查询参数的RestAdapter.Builder

    Retrofit 将为每个 API 调用调用请求拦截器,允许您附加查询参数或替换路径元素。

    在此回调中,您将能够为每个请求附加 clientIdapiKey 查询参数。

    【讨论】:

    • 这在 Retrofit 2 中不再工作 :'( 有没有办法让它回来?我必须将 api 密钥作为参数添加到对 themoviedb.org 的每次调用......
    • Edit :我在找到解决方案时为 Retrofit 2 添加了一个新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2013-08-07
    • 2017-06-15
    • 2021-10-21
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多