Rest API - how add custom headers?

那年仲夏 提交于 2021-02-19 04:33:05

问题


I want to make POST request with custom header. I can't find information how to do this using AA Rest API - https://github.com/excilys/androidannotations/wiki/Rest%20API .

Should I use ClientHttpRequestInterceptor, which is used for authenticated requests? https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client

Thanks for any help!


回答1:


There is currently an open issue for this : https://github.com/excilys/androidannotations/issues/323

For now, the only way to do this is with a custom ClientHttpRequestInterceptor. Here is a little example :

@EBean
public class CustomHeaderInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] data, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().add("myHeader", "value");
        return execution.execute(request, data);
    }

}

Then, you need to link it to the restTemplate, like this :

@EBean
public class MyService {

    @RestService
    RestClient restClient;

    @Bean
    MobileParametersInterceptor mobileParametersInterceptor;

    @AfterInject
    public void init() {
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(mobileParametersInterceptor);
        restClient.getRestTemplate().setInterceptors(interceptors);
    }

}



回答2:


Indeed you have to use the ClientHttpRequestInterceptor for custom header. Currently, it's the only way I know.

See the official documentation of Spring-Android for more informations about the RestTemplate.



来源:https://stackoverflow.com/questions/12566893/rest-api-how-add-custom-headers

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