Hi Amine,
There are a couple posts on this:
This way you can implement retries, etc
In my experience, you should have all bases covered if you implement
onError
onErrorCode(JSON/byte etc)
And then check (and retry or whatever you want to do without a popup if true)
resp.getResponseCode() != 200
resp.getResponseData() == null
If you know the expected result of a JSON response it's useful to also check it isn't null as sometimes network exceptions can return a non-null response but a null response body
Example: for a response that consists of {"result":"ok"}
You can check
((String) resp.getResponseData().get("result")) == null
A full JSON post implementation that retries automatically after waiting 1 second (and expects the above response format) would look like this
public Response<Map> safeSyncRestPost(String url, String body)
{
Boolean[] error = {false};
RequestBuilder req = Rest.post(url)
.onError(ee -> {
error[0] = true;
}, true);
if(body != null)
req.body(body);
Response<Map> resp = req.header("Content-Type", "application/json").onErrorCodeJSON(err -> {
error[0] = true;
})
.getAsJsonMap();
if (resp.getResponseCode() != 200) {
;//log error optionally
} else if (error[0]) {
;//log error optionally
} else if (resp.getResponseData() == null) {
;//log error optionally
} else if (((String) resp.getResponseData().get("result")) == null) {
;//log error optionally
} else {
return resp;//success
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
return safeSyncRestPost(url, body);//retry
}