POST主体JSON使用Retrofit

adi*_*nes 10 rest post android json retrofit

我正在尝试使用Retrofit库POST一个JSONObject,但是当我在接收端看到请求时,内容长度为0.

在RestService接口中:

@Headers({
        "Content-type: application/json"
})
@POST("/api/v1/user/controller")
void registerController( 
     @Body JSONObject registrationBundle, 
     @Header("x-company-device-token") String companyDeviceToken, 
     @Header("x-company-device-guid") String companyDeviceGuid, 
     Callback<JSONObject> cb);
Run Code Online (Sandbox Code Playgroud)

它被调用,

mRestService.registerController(
    registrationBundle, 
    mApplication.mSession.getCredentials().getDeviceToken(), 
    mApplication.mSession.getCredentials().getDeviceGuid(),
    new Callback<JSONObject>() {
        // ...
    }
)
Run Code Online (Sandbox Code Playgroud)

我确定registrationBundle,这是一个JSONObject非空或空(其他字段肯定是好的).在提出请求时,它将注销为: {"zip":19312,"useAccountZip":false,"controllerName":"mine","registrationCode":"GLD94Q"}.

在请求的接收端,我看到请求已经Content-type: application/json有了Content-length: 0.

是否有任何理由为什么在这样的身体中发送JSON不起作用?我在使用Retrofit时遗漏了一些简单的东西吗?

col*_*ots 31

默认情况下,如果需要JSON请求体,则无需设置任何标头.每当您测试Retrofit代码时,我建议您设置.setLogLevel(RestAdapter.LogLevel.FULL)RestAdapter实例.这将显示完整的请求标题和正文以及完整的响应标题和正文.

发生的是您正在设置两次Content-type.然后,你传递一个JSONObject,它正在通过GsonConverter过去了,咬伤了的样子{"nameValuePairs":YOURJSONSTRING},其中YOURJSONSTRING包含您的完整的,打算JSON输出.出于显而易见的原因,这对大多数REST API都不适用.

您应该跳过使用默认情况下已使用UTF-8设置为JSON的Content-type标头.另外,不要将JSONObject传递给GSON.传递GSON的Java对象进行转换.

如果您正在使用回调,请尝试此操作:

@POST("/api/v1/user/controller")
void registerController(
    @Body MyBundleObject registrationBundle,
    @Header("x-company-device-token") String companyDeviceToken,
    @Header("x-company-device-guid") String companyDeviceGuid,
    Callback<ResponseObject> cb);
Run Code Online (Sandbox Code Playgroud)

我没有测试过这种确切的语法.

同步示例:

@POST("/api/v1/user/controller")
ResponseObject registerController(
    @Body MyBundleObject registrationBundle,
    @Header("x-company-device-token") String companyDeviceToken,
    @Header("x-company-device-guid") String companyDeviceGuid);
Run Code Online (Sandbox Code Playgroud)