【问题标题】:Spring for Android: add get parameter to every requestSpring for Android:为每个请求添加 get 参数
【发布时间】:2015-07-16 19:38:39
【问题描述】:

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

【问题讨论】:

  • 将实际问题放在代码注释中并不是一个好主意...
  • 您可以在 ApiHttpRequest 子类中的 github.com/yDelouis/selfoss-android/blob/master/app/src/main/… 中查看我是如何做到的。我创建另一个 HttpRequest 覆盖 getURI() 以返回修改后的 URI。
  • @m0skit0 其实问题就在代码块上面。但我认为在我想要实现它的时候澄清我想要实现的目标是一个好主意。比起抱怨我的问题的风格,我会更乐于提供更有帮助的评论。
  • @yDelouis 感谢您的链接。这并不完全是我想要的,因为实际上您使用当前的 HttpRequest 创建一个新的并丢弃您之前构建的所有内容。但是你给我指明了一个好的方向。我在阅读您的解决方案时解决了我的问题。
  • @MartinH。问题的风格至关重要:如果你的问题更清楚,更多的人能够更快地理解你的问题,这直接意味着更多的人能够更快地提供帮助。很高兴你解决了它。

标签: android spring android-annotations spring-android


【解决方案1】:

事实上,就我而言,拦截器是错误的地方。因为我必须普遍应用它,并且在我看来,在创建 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());

【讨论】: