Rest API - 如何添加自定义标头? [英] Rest API - how add custom headers?
问题描述
我想使用自定义标头发出 POST 请求.我找不到如何使用 AA Rest API 执行此操作的信息 - https://github.com/excilys/androidannotations/wiki/Rest%20API.
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 .
我应该使用 ClientHttpRequestInterceptor,它用于经过身份验证的请求吗?https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client
Should I use ClientHttpRequestInterceptor, which is used for authenticated requests? https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client
感谢您的帮助!
推荐答案
目前有一个未解决的问题:https://github.com/excilys/androidannotations/issues/323
There is currently an open issue for this : https://github.com/excilys/androidannotations/issues/323
目前,唯一的方法是使用自定义 ClientHttpRequestInterceptor.这是一个小例子:
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);
}
}
然后,您需要将其链接到 restTemplate,如下所示:
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);
}
}
这篇关于Rest API - 如何添加自定义标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!