【问题标题】:Set headers using spring android resttemplate and android annotations使用 spring android resttemplate 和 android annotations 设置 headers
【发布时间】:2012-08-15 08:14:34
【问题描述】:

我目前正在使用 Spring Android Resttemplate 与 java 支持的 REST API 进行交互。实际上,我正在使用 android annotations 向这个后端服务发送 http 调用,我必须说它很震撼。基本上,Android 注释允许您为服务调用定义一个接口以及用于每个可用 api 调用的 http 方法:它将生成与编组/解编组等低级内容相关的所有样板代码,调用正确的根据接口定义的http方法。

现在,我想为 http 请求设置一些标头:知道我只有对定义所有调用的 Service 接口的引用,我该如何实现呢? 我也可以引用 RestTemplate 对象,但现在似乎有设置标题的方法。

任何帮助将不胜感激 谢谢

【问题讨论】:

    标签: android spring rest http-headers resttemplate


    【解决方案1】:

    我的方法是在应用程序类中创建ApiClient 的实例并设置自定义 REST 模板。

    在我的例子中,我使用 Jackson 进行 JSON 消息转换:

    RestTemplate restTemplate = new RestTemplate(fac);
    MappingJacksonHttpMessageConverter converter =
            new MappingJacksonHttpMessageConverter();
    converter.getObjectMapper().configure(Feature.UNWRAP_ROOT_VALUE, true);
    restTemplate
            .getMessageConverters()
            .add(converter);
    mClient.setRestTemplate(restTemplate);
    

    我的请求工厂fac 然后看起来像这样:

    ClientHttpRequestFactory fac = new HttpComponentsClientHttpRequestFactory() {
    
        @Override
        protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {
            HttpUriRequest uriRequest = super.createHttpRequest(httpMethod, uri);
            // Add request headers
            uriRequest.addHeader(
                    "Content-Type",
                    MediaType.APPLICATION_JSON_VALUE);
            return uriRequest;
        }
    
        @Override
        public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod)
                throws IOException {
            if (Config.DEBUG_REQUESTS) {
                Log.d(TAG, uri);
            }
            return super.createRequest(uri, httpMethod);
        }
    
    };
    

    警告

    尽管这适用于我们办公室的所有 Android 设备,我最近发现 所有 设备似乎都没有添加标题!我没有确定这是为什么(或具体是哪些设备),但我正在研究它,并会在找到解决方案后尝试更新此答案。

    【讨论】:

    • 非常感谢您的解释:这很有趣。我会试试这个,然后告诉你。
    • 谢谢!这就是我最终用来让 OAuth 与 Robospice 一起使用的方法
    猜你喜欢
    • 2013-06-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多