适用于Android的Spring:将参数添加到每个请求中



我正在使用Android的Spring Androidannotations。由于某些原因,API在每个请求中都需要特定的Querystring参数。所以我想通过拦截器添加它。

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);
}}

实际上,在我的情况下,拦截器是错误的地方。由于我必须一般地应用它以及在我认为HTTPRequest创建期间,这是使用我自己的请求factory实施并覆盖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);
    }
}

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

_restClient.getRestTemplate().setRequestFactory(new HttpRequestFactory());

最新更新