Android annotations REST set header

笑着哭i 提交于 2019-12-22 17:54:11

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/18366917/android-annotations-rest-set-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!