2015-05-06 183 views
1

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

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

把实际问题的代码注释使用此请求工厂不是个好主意...... – m0skit0

+1

你可以看到我是如何做到了这里的https:/ /Hithub.com/yDelouis/selfoss-android/blob/master/app/src/main/java/fr/ydelouis/selfoss/rest/SelfossApiInterceptor.java,在ApiHttpRequest子类中。我创建了另一个HttpRequest,它覆盖getURI()以返回修改后的URI。 – yDelouis

+0

@ m0skit0事实上,问题在代码块之上。但是我认为在我想实现的目标上澄清我想实现的目标是个好主意。而且,我会更乐于提供更有帮助的评论,而不仅仅是抱怨我的问题的风格。 –

回答

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()); 
相关问题