我正在尝试将数据发送到具有以下端点的服务器:https://api.test.com/sales/taken?key=1a2b3c&sales_number=abc&taken[0][id_product]=123&taken[0][qty]=123&taken[1][id_product]=123&taken[1][qty]=123
根据Android Retrofit POST ArrayList,发送列表的最佳方法是使用@Body
而不是@Field
。
所以我做了一个模型来适应这样的终点:
public class Model {
@SerializedName("key")
private String key;
@SerializedName("sales_number")
private String sales_number;
@SerializedName("taken")
private List<Taken> taken;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSales_number() {
return sales_number;
}
public void setSales_number(String sales_number) {
this.sales_number = sales_number;
}
public List<NotaAmbilDetailModel> getTaken() {
return taken;
}
public void setTaken(List<NotaAmbilDetailModel> taken) {
this.taken = taken;
}
}
和
public class Taken {
@SerializedName("id_product")
private int id_product;
@SerializedName("qty")
private int qty;
public int getId_product() {
return id_product;
}
public void setId_product(int id_product) {
this.id_product = id_product;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
我的帖子界面如下所示:
@POST("/sales/taken")
Call<ResponseModel> sendData(@Body Model model);
响应状态为:
Response{protocol=h2, code=200, message=, url=https://api.test.com/sales/taken}
。如您所见,响应代码为200,但是当我尝试获取响应正文时,发生了
java.lang.NullPointerException
。我的错误日志是:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ResponseModel.getCode()' on a null object reference
D/Response: LOG: Response{protocol=h2, code=200, message=, url=https://api.test.com/sales/taken}
Response Body: ResponseModel@bb5e4cf
最佳答案
您的api请求需要查询参数,而不是请求正文。
这样尝试
请求
@POST("/sales/taken")
Call<ResponseModel> sendData(@QueryMap Map<String, String> queryMap);
API的参数
Map<String, String> queryMap = new HashMap<>();
queryMap.put("key", "value_for_key");
queryMap.put("sales_number", "value_for_sales_number");
queryMap.put("taken[0][id_product]", "value_for_taken[0][id_product]");
queryMap.put("taken[0][qty]", "value_for_taken[0][qty]");
queryMap.put("taken[1][id_product]", "value_for_taken[1][id_product]");
queryMap.put("taken[1][qty]", "value_for_taken[1][qty]");
....