Roman
Roman

Reputation: 2079

Android annotations REST set header

I'm using Android annotations, and recently discovered a bug Spring Rest Template usage causes EOFException which I don't know how to fix using annotations. I have post request:

@Post("base/setItem.php")
Item setItem(Protocol protocol);

Now, how do I set header

headers.set("Connection", "Close");

to this request?

Thanks!

Upvotes: 2

Views: 2522

Answers (1)

DayS
DayS

Reputation: 1561

Two solutions :

Solution 1

since AA 3.0 (still in snapshot), you can use interceptors field on @Rest annotation and implement a custom ClientHttpRequestInterceptor which will set headers to each request :

public class HeadersRequestInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set("Connection", "Close");
        return execution.execute(request, body);
    }
}

Solution 2

With AA <= 2.7.1, you should create an @EBean annotated class with your Rest interface injected. Replace all injected Rest interface on other classes by this bean. In this new bean, create an @AfterInject method which will retrieve the RestTemplate instance and configure the interceptor of solution 1 :

RestClient.java :

@Rest(...)
public interface RestClient {
    @Post("base/setItem.php")
    Item setItem(Protocol protocol);

    RestTemplate getRestTemplate();
}

RestClientProxy.java :

@EBean
public class RestClientProxy {
    @RestService
    RestClient restClient;

    @AfterInject
    void init() {
        RestTemplate restTemplate = restClient.getRestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        interceptors.add(new HeadersRequestInterceptor());
    }
}

Upvotes: 7

Related Questions