如何在 Retrofit 请求正文中 POST 原始整个 JSON?

2023-12-31

这个问题之前可能已经被问过,但没有得到明确的答案。到底如何在 Retrofit 请求的正文中发布原始的整个 JSON?

查看类似问题here https://stackoverflow.com/questions/19099536/post-body-json-using-retrofit。或者这个答案是否正确必须进行表单 url 编码并作为字段传递 https://stackoverflow.com/questions/18908175/retrofit-body-showing-up-as-parameter-in-http-request?rq=1?我真的希望不会,因为我连接到的服务只是期望帖子正文中包含原始 JSON。它们未设置为查找 JSON 数据的特定字段。

我只是想澄清这一点雷斯特佩茨一劳永逸。一个人回答不使用Retrofit。另一个人不确定语法。另一个人认为是的,它可以完成,但前提是它的形式 url 编码并放置在一个字段中(这在我的情况下是不可接受的)。不,我无法为我的 Android 客户端重新编码所有服务。是的,在大型项目中发布原始 JSON 而不是将 JSON 内容作为字段属性值传递是很常见的。让我们把事情做好并继续前进。有人可以指出说明如何完成此操作的文档或示例吗?或者提供一个可以/不应该这样做的正当理由。

更新:我可以百分百肯定地说一件事。你可以在 Google 的 Volley 中做到这一点。它是内置的。我们可以在 Retrofit 中做到这一点吗?


The @Body http://square.github.io/retrofit/javadoc/retrofit/http/Body.html注释定义单个请求主体。

interface Foo {
  @POST("/jayson")
  FooResponse postJson(@Body FooRequest body);
}

由于Retrofit默认使用Gson,FooRequest实例将被序列化为 JSON 作为请求的唯一正文。

public class FooRequest {
  final String foo;
  final String bar;

  FooRequest(String foo, String bar) {
    this.foo = foo;
    this.bar = bar;
  }
}

呼叫方式:

FooResponse = foo.postJson(new FooRequest("kit", "kat"));

将产生以下主体:

{"foo":"kit","bar":"kat"}

The Gson 文档 https://sites.google.com/site/gson/gson-user-guide有关对象序列化如何工作的更多信息。

现在,如果您真的想自己发送“原始”JSON 作为正文(但请使用 Gson!)您仍然可以使用TypedInput:

interface Foo {
  @POST("/jayson")
  FooResponse postRawJson(@Body TypedInput body);
}

类型化输入 http://square.github.io/retrofit/javadoc/retrofit/mime/TypedInput.html被定义为“具有关联 mime 类型的二进制数据”。通过上述声明,有两种方法可以轻松发送原始数据:

  1. Use 类型字节数组 http://square.github.io/retrofit/javadoc/retrofit/mime/TypedByteArray.html发送原始字节和 JSON mime 类型:

    String json = "{\"foo\":\"kit\",\"bar\":\"kat\"}";
    TypedInput in = new TypedByteArray("application/json", json.getBytes("UTF-8"));
    FooResponse response = foo.postRawJson(in);
    
  2. 子类类型字符串 http://square.github.io/retrofit/javadoc/retrofit/mime/TypedString.html创建一个TypedJsonString class:

    public class TypedJsonString extends TypedString {
      public TypedJsonString(String body) {
        super(body);
      }
    
      @Override public String mimeType() {
        return "application/json";
      }
    }
    

    然后使用类似于 #1 的该类的实例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Retrofit 请求正文中 POST 原始整个 JSON? 的相关文章

随机推荐