1

我正在将 AndroidAnnotations 与 Spring for Android 一起使用。由于某些原因,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);
}}
4

1 回答 1

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());
于 2015-05-07T07:40:41.610 回答