这个问题以前可能被问过,但没有明确的答案。如何在Retrofit请求的主体中发布原始的整个JSON ?

在这里看到类似的问题。或者这个答案是正确的,它必须是表单url编码并作为一个字段传递?我真的希望不是,因为我要连接的服务只是希望在文章正文中有原始JSON。它们不是用来为JSON数据寻找特定字段的。

I just want to clarify this with the restperts once and for all. One person answered not to use Retrofit. The other was not certain of the syntax. Another thinks yes it can be done but only if its form url-encoded and placed in a field (that's not acceptable in my case). No, I can't re-code all the services for my Android client. And yes, it's very common in major projects to post raw JSON instead of passing over JSON content as field property values. Let's get it right and move on. Can someone point to the documentation or example that shows how this is done? Or provide a valid reason why it can/should not be done.

更新:有一件事我可以百分之百确定。你可以在谷歌的Volley中做到这一点。这是与生俱来的。我们可以在Retrofit中这样做吗?


当前回答

这是我在当前版本的2.6.2中工作的地方,

首先,我们需要添加一个Scalars Converter到我们的Gradle依赖项列表中,它负责将java.lang.String对象转换为文本/纯请求体,

implementation'com.squareup.retrofit2:converter-scalars:2.6.2'

然后,我们需要将一个转换器工厂传递给我们的Retrofit构建器。它稍后将告诉Retrofit如何转换传递给服务的@Body参数。

private val retrofitBuilder: Retrofit.Builder by lazy {
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
}

注:在我的改造建设者我有两个转换器Gson和 标量,你可以使用他们,但发送Json的主体,我们需要 focus Scalars,所以如果你不需要Gson删除它

然后用String体参数对服务进行翻新。

@Headers("Content-Type: application/json")
@POST("users")
fun saveUser(@Body   user: String): Response<MyResponse>

然后创建JSON主体

val user = JsonObject()
 user.addProperty("id", 001)
 user.addProperty("name", "Name")

呼叫您的服务

RetrofitService.myApi.saveUser(user.toString())

其他回答

我特别喜欢Jake对上面TypedString子类的建议。实际上,您可以基于计划推送的POST数据类型创建各种子类,每个子类都有自己的自定义一致调整集。

您还可以选择在您的Retrofit API中为您的JSON POST方法添加头注释…

@Headers( "Content-Type: application/json" )
@POST("/json/foo/bar/")
Response fubar( @Body TypedString sJsonBody ) ;

但是使用子类显然是自文档化的。

@POST("/json/foo/bar")
Response fubar( @Body TypedJsonString jsonBody ) ;

我们也可以直接使用HashMap<String, Object>来发送主体参数,而不是类 例如

interface Foo {
  @POST("/jayson")
  FooResponse postJson(@Body HashMap<String, Object> body);
}

这是我在当前版本的2.6.2中工作的地方,

首先,我们需要添加一个Scalars Converter到我们的Gradle依赖项列表中,它负责将java.lang.String对象转换为文本/纯请求体,

implementation'com.squareup.retrofit2:converter-scalars:2.6.2'

然后,我们需要将一个转换器工厂传递给我们的Retrofit构建器。它稍后将告诉Retrofit如何转换传递给服务的@Body参数。

private val retrofitBuilder: Retrofit.Builder by lazy {
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
}

注:在我的改造建设者我有两个转换器Gson和 标量,你可以使用他们,但发送Json的主体,我们需要 focus Scalars,所以如果你不需要Gson删除它

然后用String体参数对服务进行翻新。

@Headers("Content-Type: application/json")
@POST("users")
fun saveUser(@Body   user: String): Response<MyResponse>

然后创建JSON主体

val user = JsonObject()
 user.addProperty("id", 001)
 user.addProperty("name", "Name")

呼叫您的服务

RetrofitService.myApi.saveUser(user.toString())

如果你不想创建额外的类或使用JSONObject,你可以使用HashMap。

改造接口:

@POST("/rest/registration/register")
fun signUp(@Body params: HashMap<String, String>): Call<ResponseBody>

电话:

val map = hashMapOf(
    "username" to username,
    "password" to password,
    "firstName" to firstName,
    "surname" to lastName
)

retrofit.create(TheApi::class.java)
     .signUp(map)
     .enqueue(callback)

解决了我的问题基于TommySM的答案(见前)。 但是我不需要登录,我使用Retrofit2来测试https GraphQL API,就像这样:

Defined my BaseResponse class with the help of json annotations (import jackson.annotation.JsonProperty). public class MyRequest { @JsonProperty("query") private String query; @JsonProperty("operationName") private String operationName; @JsonProperty("variables") private String variables; public void setQuery(String query) { this.query = query; } public void setOperationName(String operationName) { this.operationName = operationName; } public void setVariables(String variables) { this.variables = variables; } } Defined the call procedure in the interface: @POST("/api/apiname") Call<BaseResponse> apicall(@Body RequestBody params); Called apicall in the body of test: Create a variable of MyRequest type (for example "myLittleRequest"). Map<String, Object> jsonParams = convertObjectToMap(myLittleRequest); RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), (new JSONObject(jsonParams)).toString()); response = hereIsYourInterfaceName().apicall(body).execute();