我是改造库中的新手。每次尝试通过Retrofit发送POST请求时,我都会遇到422内部服务器错误。我的代码出了什么问题?
MainActivity.java
public void setFruit()
{
List<Fruit> list = new ArrayList<>();
if(name.getText() != null)
{
Fruit fruit = new Fruit();
fruit.setName(name.getText().toString());
fruit.setColor(color.getText().toString());
fruit.setWeight(weight.getText().toString());
fruit.setDelicious(delicious);
list.add(fruit);
showPDialog();
Toast.makeText(MainActivity.this, "GetData Clicked", Toast.LENGTH_SHORT).show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.100:8000/api/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<Fruit> call = service.insertFruit(list);
call.enqueue(new Callback<Fruit>() {
@Override
public void onResponse(Response<Fruit> response, Retrofit retrofit) {
printSuccess(""+response.code());
hidePDialog();
}
@Override
public void onFailure(Throwable t) {
hidePDialog();
}
});
}
else
{
Toast.makeText(this, "Fill all the fields", Toast.LENGTH_SHORT).show();
}
}
APIService.java
public interface APIService {
@GET("fruits")
Call<Fruits> getFruitDetails();
@POST("fruits")
Call<Fruit> insertFruit(
@Body
List<Fruit> fruit
);}
邮政要求在Postman中运作良好。
更新
我找到了解决方法。我尝试使用JsonObject而不是使用java对象。
public void setFruit()
{
if(name.getText() != null && color.getText() != null && weight.getText() != null)
{
JsonObject object = new JsonObject();
object.addProperty("name",name.getText().toString());
object.addProperty("color",color.getText().toString());
object.addProperty("weight",weight.getText().toString());
object.addProperty("delicious","1");
Log.wtf("TAG",object.toString());
showPDialog();
Toast.makeText(MainActivity.this, "Insert Data Clicked", Toast.LENGTH_SHORT).show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JsonObject> call = service.insertFruit(object);
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
printSuccess(""+response.message());
hidePDialog();
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
hidePDialog();
}
});
}
else
{
Toast.makeText(this, "Fill all the fields", Toast.LENGTH_SHORT).show();
}
}
这很好用:)。谢谢!