Rest API - 如何添加自定义标头?

时间:2012-09-24 14:17:36

标签: android resttemplate android-annotations

我想使用自定义标头发出POST请求。我无法使用AA Rest API - https://github.com/excilys/androidannotations/wiki/Rest%20API找到有关如何执行此操作的信息。

我应该使用ClientHttpRequestInterceptor,它用于经过身份验证的请求吗? https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

目前存在一个未解决的问题:https://github.com/excilys/androidannotations/issues/323

目前,唯一的方法是使用自定义ClientHttpRequestInterceptor。这是一个小例子:

@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,如下所示:

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

}

答案 1 :(得分:1)

实际上,您必须将ClientHttpRequestInterceptor用于自定义标头。 目前,这是我所知道的唯一方式。

有关RestTemplate的更多信息,请参阅Spring-Android的官方documentation