1

I'm using AndroidAnnotations with Spring for Android. For some reasons, the API needs a specific QueryString-Parameter in every request. So I want to add it via an interceptor.

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);
}}
kryger
  • 12,906
  • 8
  • 44
  • 65
Martin H.
  • 1,086
  • 1
  • 17
  • 28
  • Putting the actual question in a code comment is not a good idea... – m0skit0 May 06 '15 at 15:22
  • 1
    You can see how I did it here https://github.com/yDelouis/selfoss-android/blob/master/app/src/main/java/fr/ydelouis/selfoss/rest/SelfossApiInterceptor.java, in the ApiHttpRequest subclass. I create another HttpRequest which overrides getURI() to return a modified URI. – yDelouis May 06 '15 at 15:48
  • @m0skit0 In fact the question is above the code block. But I thought it's a good idea to clarify what I want to achieve at the point where I want to achieve it. And I would have been happier with a more helpful comment than just complaining about the style of my question. – Martin H. May 07 '15 at 07:33
  • @yDelouis Thanks for the link. It is not exactly what I want as in fact you use the current HttpRequest to create a new one and throw away everything you build up before. But you pointed me into a good direction. I solved my problem while I read your solution. – Martin H. May 07 '15 at 07:35
  • @MartinH. The style of the question is of utmost importance: if your question is more clear, more people would be able to understand faster what you're asking, which directly implies more people would be able to help faster. Glad you solved it anyway. – m0skit0 May 07 '15 at 07:58

1 Answers1

2

In fact in my case the interceptor was the wrong place to do this. as I have to apply it generally and during the creation of the HttpRequest in my opinion it's a better approach to use my own implementation of the RequestFactory and override the createHttpRequest method.

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

and use this request factory in my rest client

_restClient.getRestTemplate().setRequestFactory(new HttpRequestFactory());
Martin H.
  • 1,086
  • 1
  • 17
  • 28