【发布时间】:2018-08-30 21:30:54
【问题描述】:
当我通过邮递员作为行请求(Json)发送请求时,我得到了成功响应,但从我的 android 设备上它没有成功。
这是我的 Android 代码,
接口ApiService.Class
@Headers("Content-Type: application/json")
@POST("api/ShopData/AddProduct")
Call<AddNewProductResponse> addNewProduct(@Header("Authorization") String authorization, @Body JsonObject jsonObject);
班级ApiClient.Class
public static Call<AddNewProductResponse> addNewProduct(String token, JsonObject jsonObject) {
token = "Bearer " + token;
Call<AddNewProductResponse> call = apiService.addNewProduct(token, jsonObject);
return call;
}
API 调用
private void addNewProductToServer(JsonObject jsonObject) {
String token = AppSettings.getInstance(getActivity()).getStringValue(PrefKeys.token);
if (token != null && jsonObject != null) {
ApiClient.addNewProduct(token, jsonObject).enqueue(new Callback<AddNewProductResponse>() {
@Override
public void onResponse(Call<AddNewProductResponse> call, retrofit2.Response<AddNewProductResponse> response) {
if (response != null && response.body() != null) {
if (response.body().getMessage().getCode() == 1) {
showProductAddedSuccessDialog();
} else
Helper.showAlertDialogOK(getActivity(), Helper.getErrorMessages(response.body().getMessage().getCode()));
} else
Helper.showServerErrorDialog(getActivity());
}
@Override
public void onFailure(Call<AddNewProductResponse> call, Throwable t) {
Helper.showServerErrorDialog(getActivity());
}
});
}
}
创建请求JsonObject,
JsonObject jsonObject = new JsonObject();
JsonArray images = new JsonArray();
try {
if (productImage != null) {
JsonObject imgObject = new JsonObject();
imgObject.addProperty("attachment", productImage.getAttachment());
imgObject.addProperty("position", 1);
images.add(imgObject);
}
jsonObject.addProperty("name", edtTxtProductName.getText().toString().trim());
jsonObject.addProperty("short_description", edtTxtShortDescription.getText().toString().trim());
jsonObject.addProperty("full_description", edtTxtLongDescription.getText().toString().trim());
jsonObject.addProperty("sku", edtTxtSku.getText().toString().trim());
jsonObject.addProperty("stock_quantity", Integer.parseInt(edtTxtStockQuantity.getText().toString().trim()));
jsonObject.addProperty("price", Float.parseFloat(edtTxtPrice.getText().toString().trim()));
jsonObject.addProperty("images", String.valueOf(images));
addNewProductToServer(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
【问题讨论】:
-
路过时用
jsonObject.toString()试试 -
@RaviRupareliya 我需要将 Body 作为字符串传递,对吗?
-
是的,简而言之就是你的 jsonObject
-
为什么不将 PoJo 与 GSON 一起使用?
-
@RaviRupareliya 不,它不工作,我修改喜欢,----ApiService.Class----- Call
addNewProduct(Header("Authorization") 字符串授权,正文字符串 jsonObject) ----ApiClient.Class------ apiService.addNewProduct(token, jsonObject.toString());
标签: android retrofit2 jsonobjectrequest