Spring для Android: добавьте параметр get к каждому запросу

Я использую Android Аннотации с Spring для 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);
}}

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

и использовать эту фабрику запросов в моем клиенте отдыха

_restClient.getRestTemplate().setRequestFactory(new HttpRequestFactory());
Другие вопросы по тегам