gson 当我的API回复404时,Retrofit返回空

yv5phkfx  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(187)

我有一个API。它返回404时,它没有数据库中的数据。Retrofit 2返回空响应时,我的API返回404作为响应代码。
Barcode.activity:

LnkBarcodeBaptizeCheckModel lnkModel = new LnkBarcodeBaptizeCheckModel();
                        List<String> bap_barcodes = new ArrayList<String>();
                        bap_barcodes.add(barcode);
                        lnkModel.bap_barcodes = bap_barcodes;Call<LnkBarcodeBaptizeCheckResponseModel> lnkCall = apiInterface.CheckLnkBarcodeBaptizeTable(lnkModel);
                        LnkBarcodeBaptizeCheckResponseModel lnkResponse = new MainAynscTask<LnkBarcodeBaptizeCheckResponseModel>().execute(lnkCall).get();

委托单位:

private static Retrofit retrofit = null;

public static Retrofit getClient() {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    Gson gson = new GsonBuilder().create();

    retrofit = new Retrofit.Builder()
            .baseUrl("http://localserver/IndustrialApplicationsAPI/api/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build();


    return retrofit;
}

}
发布方法:

@POST("CuringPhase/CheckLnkBarcodeBaptizeTable")
Call<LnkBarcodeBaptizeCheckResponseModel> CheckLnkBarcodeBaptizeTable(@Body LnkBarcodeBaptizeCheckModel trcModel);

改装电话:

public class MainAynscTask<T> extends AsyncTask<Call<T>, Void, T> {

@Override
protected T doInBackground(Call<T>... call) {
    T responseModel = null;
    try {
        responseModel = call[0].execute().body();
    } catch (IOException e) {
        System.out.println("Call error: " + e.getLocalizedMessage());
    }
    return responseModel;
}

@Override
protected void onPostExecute(T result) {
    super.onPostExecute(result);
    //how i will pass this result where i called this task?
}

}
实际上,我得到响应,但它不解析.
{“响应代码”:404,“数据”:[],“错误”:{“错误代码”:404,“错误说明”:“未找到!"}}〈-- END HTTP(81字节正文)

API Response:
{
  "responseCode": 404,
  "data": [

  ],
  "error": {
    "errorCode": 404,
    "errorDesc": "Not found!"
  }
}

原因何在?
顺便说一下,它解析响应时,我只是改变响应代码为200.

7jmck4yq

7jmck4yq1#

响应代码404表示应用程序可以与给定的服务器通信,但是服务器找不到请求的内容。我建议您查看一下您的API请求参数,以及后端如何处理这些请求

编辑日期:

可以使用JSONObject解析错误响应(如果要发送一个)

JSONObject erroObj = new JSONObject(response.errorBody().string());

// or if you have an custom error model class then do this
Gson gson = new Gson();
Type type = new TypeToken<YourErrorResponseClass>() {}.getType();
YourErrorResponseClass errorResponse = 
gson.fromJson(response.errorBody(),type);

我希望这就是你要找的

相关问题