android - 带有 AndroidAnnotations 的 Rest 客户端 - "no suitable HttpMessageConverter..."

标签 android gson resttemplate android-annotations


我想向服务器发送 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);

休息客户端

@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 吗?
或者我应该使用 Jackson?
那我需要包含哪个文件呢?

感谢您的帮助!

最佳答案

您可以将 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);

关于android - 带有 AndroidAnnotations 的 Rest 客户端 - "no suitable HttpMessageConverter...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12405184/

相关文章:

java - Android 上的 SimpleDateFormat 时区错误

dart - 什么是类似 java 中的 Gson 的 flutter dart 中可用的等效库

java - Spring RestTemplate 遵循带有 cookie 的重定向

rest - restTemplate.exchange()方法有什么作用?

java - 如何动态调用基类中由字符串值指定的子类方法?

android - 如何在 Android 上链接 .so 库

android - Android WebView调整默认音频播放器的大小

java - 使用 MongoRepository 自定义反序列化器

java - Gson NumberFormatException

java - RestTemplate 不转义 url