我在Android的Spring上使用AndroidAnnotations。由于某些原因,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);
}}

最佳答案

实际上,就我而言,拦截器是执行此操作的错误位置。因为我认为通常必须在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());

关于android - Android版Spring:向每个请求添加get参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30080610/

10-11 22:31
查看更多