I have an API. It returns 404 when it does not data in Database. Retrofit 2 returns null response when my API returns 404 as response code.
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();
Client:
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 method:
@POST("CuringPhase/CheckLnkBarcodeBaptizeTable")
Call<LnkBarcodeBaptizeCheckResponseModel> CheckLnkBarcodeBaptizeTable(@Body LnkBarcodeBaptizeCheckModel trcModel);
Retrofit Call:
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?
}
}
Actually, I get response but It does not parsing.
{"responseCode":404,"data":[],"error":{"errorCode":404,"errorDesc":"Not found!"}} <-- END HTTP (81-byte body)
API Response:
{
"responseCode": 404,
"data": [
],
"error": {
"errorCode": 404,
"errorDesc": "Not found!"
}
}
What is the reason?
By the way, It parses the response when I just change the response code to 200.
CodePudding user response:
It may be because of some parsing issue.
If you can share your code than it will be helpful in digging out the cause of error.
CodePudding user response:
Response code 404 means that app was able to communicate with a given server, but the server could not find what was requested. Might I suggest that you take a look at your api request parameters and how is the backend handling those requests
Edited:
You can parse your error response(if you are sending one) by using 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);
I hope this is what you were looking for