【发布时间】:2019-12-31 09:25:00
【问题描述】:
我正在尝试使用 Retrofit2 实现一个 put 方法来更新演示 API 的记录,但它没有在回调中给我响应并跳转到 onFailure 函数。
- 我正在使用演示 APi (http://dummy.restapiexample.com/update)
- 我有一个响应类 UpdateResponse
- 我有一个 Api 类和一个 ApiInterface
- 和一个对话框而不是主要活动
- 在ApiInterface中使用PUT方法有一个@path(id)和三个@fields(name,salary,age)
UpdateResponse 类代码如下
public class UpdateResponse {
@SerializedName("id")
@Expose
private int id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("salary")
@Expose
private String salary;
@SerializedName("age")
@Expose
private String age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String employeeName) {
this.name = employeeName;
}
public String getSalary() {
return salary;
}
public void setSalary(String employeeSalary) {
this.salary = employeeSalary;
}
public String getAge() {
return age;
}
public void setAge(String employeeAge) {
this.age = employeeAge;
}
}
API接口代码如下
public interface ApiInterface {
@FormUrlEncoded
@PUT("api/v1/update/{id}")
Call<UpdateResponse> updateUser(@Path("id") int id,
@Field("name") String name,
@Field("salary") String salary,
@Field("age") String age);
}
API 类代码如下
public class Api {
private static Retrofit retrofit = null;
public static ApiInterface getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://dummy.restapiexample.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
ApiInterface api = retrofit.create(ApiInterface.class);
return api;
}
}
下面是作为主要活动代码的对话框
String nameStr = name.getText().toString();
String salaryStr = salary.getText().toString();
String ageStr = age.getText().toString();
//idd is getting from mainActivity onitemSelect method, which is having the right id value
Call<UpdateResponse> call= Api.getClient().updateUser(idd,nameStr,salaryStr,ageStr);
call.enqueue(new Callback<UpdateResponse>() {
@Override
public void onResponse(Call<UpdateResponse> call, Response<UpdateResponse> response) {
Toast.makeText(c.getApplicationContext(),"Updated Name: "+response.body().getName(),Toast.LENGTH_LONG).show();
dismiss();
}
@Override
public void onFailure(Call<UpdateResponse> call, Throwable t) {
Toast.makeText(c.getApplicationContext(),"Failure",Toast.LENGTH_LONG).show();
dismiss();
}
});
在响应调用中显示:
call: ExecuterCallAdapterFactory$ExecuterCallbackCall@5922" 并在 Throwable t 中显示为“com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 27 path $.error.
【问题讨论】:
-
No Radesh,这不是我的问题的解决方案,请看问题的结尾,我有一些修改
-
看起来您的响应 json 与您的 UpdateResponse 结构不匹配。