Retrofit添加公共请求参数以及添加自定义的ConverterFactory

public class HttpBaseInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        // 添加新的参数
        HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                .newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host());
        Request.Builder builder = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body());

        authorizedUrlBuilder.addQueryParameter("salt", UserService.getInstance().getSalt());
        authorizedUrlBuilder.addQueryParameter("user_id", UserService.getInstance().getUserid());

        // 新的请求
        Request newRequest = builder.url(authorizedUrlBuilder.build()).build();
        Response response;
        try {
            response = chain.proceed(newRequest);
        } catch (Exception e) {
            throw e;
        }
        //这个是因为,如果请求下载链接的话,会导致无法获取response
        BufferedSource source = response.body().source();
        source.request(Long.MAX_VALUE);
        return response;

    }
}

以下是添加自定义处理response的ConverterFactory,处理返回的结果

public class StringConverterFactory extends Converter.Factory {
    public static StringConverterFactory create() {
        return new StringConverterFactory();
    }

    @Override
    public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        //Retrofit并不是自动去判断返回的类型,依旧是需要指定的,能处理就处理,不能处理就返回null
        if(type==String.class){
            return new Converter() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    return value.string();
                }
            };
        }else return null;
    }
}

你可能感兴趣的:(Retrofit添加公共请求参数以及添加自定义的ConverterFactory)