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 类型的二进制数据”。通过上述声明,有两种方法可以轻松发送原始数据:
-
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);
-
子类类型字符串 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 的该类的实例。