Spring for Android:为每个请求添加get参数
我将AndroidAnnotations与Spring一起用于Android。出于某些原因,API在每个请求中都需要一个特定的QueryString参数。所以我想通过拦截器添加它Spring for Android:为每个请求添加get参数,android,spring,android-annotations,spring-android,Android,Spring,Android Annotations,Spring Android,我将AndroidAnnotations与Spring一起用于Android。出于某些原因,API在每个请求中都需要一个特定的QueryString参数。所以我想通过拦截器添加它 公共类TestInterceptor实现ClientHttpRequestInterceptor{ @凌驾 公共ClientHttpResponse截获(HttpRequest HttpRequest,字节[]字节,ClientHttPrequesteExecution ClientHttPrequesteExecut
公共类TestInterceptor实现ClientHttpRequestInterceptor{
@凌驾
公共ClientHttpResponse截获(HttpRequest HttpRequest,字节[]字节,ClientHttPrequesteExecution ClientHttPrequesteExecution)引发IOException{
//如何在此处安全地将常量querystring参数添加到httpRequest?
//例如。http://myapi/test -> http://myapi/test?key=12345
//例如。http://myapi/test?name=myname -> http://myapi/test?name=myname&key=12345
return clienthttpprequestexecution.execute(httpRequest,字节);
}}
事实上,在我的例子中,拦截器是执行此操作的错误位置。因为我必须在创建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);
}
}
并在我的rest客户机中使用此请求工厂
_restClient.getRestTemplate().setRequestFactory(new HttpRequestFactory());
将实际问题放在代码注释中不是一个好主意……您可以在这里的ApiHttpRequest子类中看到我是如何做到这一点的。我创建了另一个HttpRequest,它重写getURI()以返回修改后的URI。@m0skit0事实上,问题在代码块上方。但我认为在我想要实现的时候澄清我想要实现什么是个好主意。如果有更有用的评论,我会更高兴,而不仅仅是抱怨我问题的风格。@Louis,谢谢你的链接。这并不完全是我想要的,因为事实上,您使用当前的HttpRequest创建了一个新的HttpRequest,并丢弃了以前构建的所有内容。但你给我指出了一个好的方向。“我在读你的解决方案时解决了我的问题。”马丁。问题的风格至关重要:如果你的问题更清楚,更多的人能够更快地理解你的问题,这直接意味着更多的人能够更快地提供帮助。很高兴你解决了这个问题。