Post后的RetroFit响应参数

时间:2017-02-23 00:04:56

标签: java retrofit

在下面的代码中,我使用RetroFit2将对象发布到端点:http://localhost:3000/insert:

Call<DeviceModel> deviceModelCall = api.createDevice(device);
deviceModelCall.enqueue(new Callback<DeviceModel>() {
    @Override
    public void onResponse(Call<DeviceModel> call, Response<DeviceModel>
                                response) {
        //How do I get access to the {"success" : true} object sent as a response form the endpoint after I posted.
    }

    @Override
    public void onFailure(Call<DeviceModel> call, Throwable t) {
        Log.d("Failure", "ON FAILURE" + "Failure");
    }
});

现在在我的Node API中,如果对象的保存成功,我将返回一个JSON对象:{"success" : true}

但在上述onResponse方法中,参数中的response变量属于Response<DeviceModel>类型。如何从{"success" : true}中的上述方法中提取我从以下节点API发回的onResponse()对象?有没有办法做到这一点?

router.post('/insert', function(req, res) {
    //Create Object
    var obj = new Device({
    });

    obj.save(function(err) {
        if (err) {
            console.log("SAVE NOT SUCCESSFUL"); 
        }else {
            console.log("SAVE SUCCESS");
            res.json({
                "success" : true
            });
        }
    });
});

1 个答案:

答案 0 :(得分:1)

你应该转到OkHTTP文档,这是Retrofit在引擎盖下使用的文档。

response.body()应该为您提供DeviceModel,对于只有boolean success字段的类来说,这似乎是一个奇怪的名称,所以我认为您的Retrofit API Design需要一些工作......

注意:响应正文只能消费一次必须关闭

例如,尝试使用资源

   Call<DeviceModel> call = client.newCall(request);
   call.enqueue(new Callback<DeviceModel>() {
     public void onResponse(Call<DeviceModel> call, Response<DeviceModel> response) throws IOException {
       try (DeviceModel model = response.body()) {
         // TODO: use model
       }
     }

     public void onFailure(Call call, IOException e) {
       ... // Handle the failure.
     }
   });

来源 - ResponseBody

如果您真的需要,可以使用response.body().string()获取原始JSON字符串。

相关问题