Android for Spring:为每个请求添加get参数

时间:2015-05-06 15:05:41

标签: android spring android-annotations spring-android

我在Android上使用AndroidAnnotations和Spring。由于某些原因,API在每个请求中都需要特定的QueryString-Parameter。所以我想通过拦截器添加它。

public class TestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

    // how to safely add a constant querystring parameter to httpRequest here?
    // e.g. http://myapi/test -> http://myapi/test?key=12345
    // e.g. http://myapi/test?name=myname -> http://myapi/test?name=myname&key=12345

    return clientHttpRequestExecution.execute(httpRequest, bytes);
}}

1 个答案:

答案 0 :(得分:2)

事实上在我的情况下,拦截器是错误的地方。因为我必须一般地应用它,并且在我认为创建HttpRequest期间,使用我自己的RequestFactory实现并覆盖createHttpRequest方法是一种更好的方法。

public class HttpRequestFactory extends HttpComponentsClientHttpRequestFactory {

    @Override
    protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {
        String url = uri.toString();
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("key", "1234");
        URI newUri = builder.build().toUri();
        return super.createHttpRequest(httpMethod, newUri);
    }
}

并在我的休息客户端中使用此请求工厂

_restClient.getRestTemplate().setRequestFactory(new HttpRequestFactory());
相关问题