【问题标题】:Rest Client with AndroidAnnotations - "no suitable HttpMessageConverter..."使用 AndroidAnnotations 休息客户端 - “没有合适的 HttpMessageConverter ...”
【发布时间】:2012-09-13 11:26:52
【问题描述】:


我想向服务器发送 POST 请求。我必须将 JSON 对象作为参数传递,并获取 JSON 作为响应,但我收到此错误:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.package.Response] and content type [application/octet-stream]

代码

发送请求:

    @RestService
    RestClient restClient;
...
    String json = "{\"param\":3}"; 
    restClient.getRestTemplate().getMessageConverters().add(new GsonHttpMessageConverter());
    Response res = restClient.send(json);

RestClient

@Rest("http://my-url.com")

    public interface RestClient
    {
        @Post("/something/")
        Response send(String json);

        RestTemplate getRestTemplate();

        void setRestTemplate(RestTemplate restTemplate);
    }

我正在使用这些 JAR 文件:

  • spring-android-rest-template-1.0.0.RC1
  • spring-android-core-1.0.0.RC1
  • spring-android-auth-1.0.0.RC1
  • gson-2.2.2

我做错了什么?
当我将 send 参数更改为 JSONObject 时,我遇到了同样的错误。
顺便提一句。 AA 文档真的很神秘——我可以使用 Gson 吗?
或者我应该使用杰克逊?
那么我需要包含哪个文件?

感谢您的帮助!

【问题讨论】:

    标签: android gson resttemplate android-annotations


    【解决方案1】:

    您可以将 RestTemplate 与 Gson 或 Jackson 一起使用。

    Gson 很好,更容易使用你有小的 json 数据集。如果你有一个复杂/深的 json 树,Jackson 更合适,因为 Gson 会创建很多临时对象,这会导致世界 GC 停止。

    这里的错误说它找不到能够解析application/octet-streamHttpMessageConverter

    如果您查看 GsonHttpMessageConverter 的源代码,您会注意到它仅支持 mimetype application/json

    这意味着您有两种选择:

    • 从您的内容中返回 application/json mimetype,这将非常合适
    • 或者只是更改GsonHttpMessageConverter 上支持的媒体类型:
    String json = "{\"param\":3}"; 
    GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
    converter.setSupportedMediaTypes(new MediaType("application", "octet-stream", Charset.forName("UTF-8")));
    restClient.getRestTemplate().getMessageConverters().add(converter);
    Response res = restClient.send(json);
    

    【讨论】:

    • 非常感谢!新版 AA 会支持 HttpMessageConverters 的注解吗?
    • 是的,这是计划的一部分 :)
    • 酷,谢谢 Piwaï。如果其他人需要它,请提供更多信息:为了添加它,我放弃了从接口自动生成的 RestClient 并使用生成的类作为基础 - 然后将上面的 Piwaï 代码添加到构造函数中。除了我, setSupportedMediaTypes 需要一个 MediaTypes 列表,所以我首先将 MediaType 添加到一个列表中。然后,您可以将 \@RestClient 切换为 \@EBean 并使用 \@Bean 引用您的类。反正为我工作! :)
    【解决方案2】:

    我刚遇到这个问题。几个小时后,我意识到我传递给 RestTemplate.postForObject 调用的类有 Date 变量。您需要确保它只包含简单的数据类型。希望这对其他人有帮助!

    【讨论】:

      【解决方案3】:

      我必须稍微修改一下才能工作:

      final List<MediaType> list = new ArrayList<>();
      list.addAll(converter.getSupportedMediaTypes());
      list.add(MediaType.APPLICATION_OCTET_STREAM);
      converter.setSupportedMediaTypes(list);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 2014-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多