【问题标题】:Rest API - how add custom headers?Rest API - 如何添加自定义标头?
【发布时间】:2012-09-24 14:17:36
【问题描述】:

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

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

感谢您的帮助!

【问题讨论】:

    标签: android resttemplate android-annotations


    【解决方案1】:

    目前有一个未解决的问题: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);
        }
    
    }
    

    【讨论】:

      【解决方案2】:

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

      更多关于 RestTemplate 的信息请见 Spring-Android 官方documentation

      【讨论】:

        猜你喜欢
        • 2013-05-15
        • 1970-01-01
        • 1970-01-01
        • 2020-09-22
        • 2019-09-12
        • 2015-06-06
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        相关资源
        最近更新 更多