Java 立柱安装后的改装响应参数
在下面的代码中,我使用Reformation2将对象发布到端点:Java 立柱安装后的改装响应参数,java,retrofit,Java,Retrofit,在下面的代码中,我使用Reformation2将对象发布到端点:http://localhost:3000/insert: Call<DeviceModel> deviceModelCall = api.createDevice(device); deviceModelCall.enqueue(new Callback<DeviceModel>() { @Override public void onResponse(Call<DeviceModel
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");
}
});
您应该阅读OkHTTP文档,这是改装在引擎盖下使用的内容
response.body()
应该给你一个DeviceModel
,但是对于一个只有布尔成功
字段的类来说,这个名字似乎很奇怪,所以我认为你的改型API设计需要一些工作
注意:响应体只能使用一次,并且必须关闭
例如,尝试使用资源
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.
}
});
Call Call=client.newCall(请求);
call.enqueue(新回调(){
public void onResponse(调用调用、响应响应)引发IOException{
try(DeviceModel model=response.body()){
//TODO:使用模型
}
}
公共void onFailure(调用调用,IOE异常){
…//处理失败。
}
});
来源-
如果您确实需要原始JSON字符串,可以使用
response.body().string()
来获取它 如果响应不是设备模型
,为什么要使用调用
?哦,我的设备模型
有6个以上的字段。但是我只想用JSON对象{“success”:true}
返回一个响应。我想检查onResponse
回调中的success
键,测试它是否为真,然后在设备成功保存后在应用程序中执行一些操作。或者response.body将始终是DeviceModel对象吗?如果使用调用
,则将得到一个响应
,即DeviceModel
。您可以轻松地重新编写CreateDeviceAPI方法以返回其他真实的内容,但是,您不应该返回由数据库创建的整个对象吗?难道你不能安全地假设来自API的200响应代码是“成功的”吗?是的,我想我将用200响应代码来做这件事。我将检查onResponse()
中的响应代码,并执行任何需要的操作。谢谢你的帮助。
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.
}
});