I have used a restful API in my android application with the volley library, as I know in restful API we should implement STATUS CODES in special situation, but as I checked volley codes in this path : volley\toolbox\BasicNetwork.java I see volley only accepts status codes between 200 and 299.
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
Why?
Does this mean volley does not support RESTFUL architectural?
VolleyError has a variable of type NetworkResponse that is public. You can access error.networkResponse.statusCode to implement your http error codes.
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
// Deserialize data using what you want
JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (JSONException e2) {
e2.printStackTrace();
}
}
}
You can read more about this here. Android Volley - BasicNetwork.performRequest: Unexpected response code 400
If the server STATUS_CODE is in between 200 - 299 it is considerably a success status and Volley will fire the onResponse callback.
The code:
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
Just simply means: When the status code IS NOT IN BETWEEN 200 - 299 therefore it is an error and Volley will fire the onErrorResponse callback instead.
Related
My current success response is this:
{"status":"success","message":"msg here"}
with code 200
And my error response is this:
{"status":"failure","message":"There was a validation error","errors":{"shippingAddress":{"phoneNumber":"Please enter a valid phone number"}}}
with code 400
my problem is the code below is not working because it always go inside onFailure()
if (response.isSuccessful()) {
// do something
} else if (response.code() == 400) {
Gson gson = new Gson();
ErrorPhone message = null;
if (response.errorBody() != null) {
message = gson.fromJson(response.errorBody().charStream(), ErrorPhone.class);
}
if (message != null) {
Toast.makeText(context, message.getErrors().getShippingAddress().getPhoneNumber(), Toast.LENGTH_LONG).show();
} else {
String errors = "";
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
errors = jObjError.getJSONObject("errors").getJSONObject("shippingAddress").getString("phoneNumber");
} catch (JSONException | IOException e) {
e.printStackTrace();
}
if (!errors.equals("")) {
Toast.makeText(context, errors, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, response.message(), Toast.LENGTH_LONG).show();
}
}
}
and inside onFailure i cant listen to errorBody to handle the response
Use Retrofit interface called onResponse and place your code there. As Retrofit uses two different callback methods for the two possible outcomes of a network requests: either a failure or a successful request. Retrofit will call the appropriate callback method depending on the result. If the request was successful, Retrofit will also pass you the response of the server.
For more view this link:https://square.github.io/retrofit/2.x/retrofit/retrofit2/Callback.html and https://futurestud.io/tutorials/java-basics-for-retrofit-callbacks that will help you more to learn about retrofit Call-backs
I am trying to access REST API using OauthClient
try {
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = client.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
The api call returns a response body when I execute the call using Postman, but when I use this code above, it throws exception and I can not see the response body, in order to parse it.
Here is the exception:
org.apache.oltu.oauth2.common.exception.OAuthSystemException: java.io.IOException: Server returned HTTP response code: 409 for URL:
Is it possible to parse the response body for 4xx errors
You can build your response object in catch block and return like
} catch (Exception ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(new PresenterClass(ex.getMessage())).build();
}
Using Presenter class constructor
Public PresenterClass(String errorMessage){
this.message = errorMessage;
}
I have below code use to POST JSON object to the following URL
HttpEntity messageEntity = new HttpEntity(message, buildHttpHeaders(getTerminalId()));
String theUrl = "http://123.433.234.12/receive";
try {
System.out.println("In try block");
ResponseEntity<Dto> responseEntity= restTemplate.exchange(theUrl, HttpMethod.POST, messageEntity, Dto.class);
} catch (HttpStatusCodeException ex) {
// get http status code
}
If the URL is invalid or service unavailable, I want it throw error status code like 404 or 503. Unfortunatelly it will always stop at the try block..Is there a way to solve that ?
Output
In try block
Edit
String theUrl = "http://123.433.234.12/receive" + transactionId; //invalid Id
try {
System.out.println("=========start=========");
ResponseEntity<Dto> responseEntity= restTemplate.exchange(theUrl, HttpMethod.POST, messageEntity, Dto.class);
System.out.println("=========end=========");
} catch (HttpStatusCodeException ex) {
String a = ex.getStatusCode().toString();
System.out.println(a);
}
Output
=========start=========
2017-09-22 14:54:54 [xles-server-ThreadPool.PooledThread-0-running] ERROR c.r.abc.jpos.JposRequestListener - Error HttpStatusCode 500org.springframework.web.client.HttpServerErrorException: 500 null
It stop and not display ========end ======== or any status code in catch block
Valid url
http://abc0/receive/hello
If I change to
http://abc0/recei/hello
I will get 404 in catch block, it look fine. But when I change to another url that not exits,example
http://123.433.234.12/receive
it is in try block .Why ????
With reference to this doc, you should catch RestClientException instead of just HttpStatusCodeException.
If you want to throw exception in specific scenarios you can do it like this
try {
restTemplate.exchange(...);
}
catch (RestClientException e) {
// implies error is related to i/o.
if (e instanceof ResourceAccessException) {
// java.net.ConnectException will be wrapped in e with message "Connection timed out".
if (e.contains(ConnectException.class)) {
// handle connection timeout excp
}
} else if (e instanceof HttpClientErrorException) {
// Handle all HTTP 4xx error codes here;
} else if (e instanceof HttpServerErrorException) {
// Handle all HTTP 5xx error codes here
}
}
for HttpClientErrorException you can get error code from excption as shown below
HttpClientErrorException clientExcp = (HttpClientErrorException) e;
HttpStatus statusCode = clientExcp.getStatusCode();
like wise, you could get error code for HttpServerErrorException.
As far as I remember RestTemplate.exchange method throws RestClientException. You have HttpStatusCodeException in your catch clause, which is only one of RestClientException subclasses.
The address you're trying to reach (http://123.433.234.12/receive) is not valid address, therefore you can't get ANY response from it (no 200s but no 500s or 400s too). Try to catch RestClientException and print its message to see what is going on. Then you can write some code to manage such situations.
Moreover if that does not work, try to go step by step and check wether ResponseEntity is null and what it has in its body. That's what I'm doing when I try to understand some method ;=)
Clicking on a hyperlink is throwing me the below error.
Please suggest me how to handle this is below exception.
Use below code to check for the response code of the URL:
public static boolean getResponseCode(String chkurl) {
boolean validResponse = false;
try {
//Get response code of URL
HttpResponse urlresp = new DefaultHttpClient().execute(new HttpGet(chkurl));
int resp_Code = urlresp.getStatusLine().getStatusCode();
System.out.println("Response Code Is : "+resp_Code +" for "+chkurl);
if ((resp_Code == 404) || (resp_Code == 505)) {
validResponse = false;
} else {
validResponse = true;
}
} catch (Exception e) {
}
return validResponse;
}
I'm afraid there is no way to check do HTTP status code directly using Webdriver. You can use a HTTP client directly, but if the problem is a 500 code, or a 403, it can become unwieldy. We cover a more powerful technique using Mob Browser Proxy with WedDriver in our book:
http://selenium-webdriver-in-practice.github.io
I have simple request like
/*LOGIN*/
#FormUrlEncoded
#POST("v1/user/login") //your login function in your api
Call<LoginResponce> login(#Field("identity") String identity,
#Field("password") String password);
Which returns either LoginResponceobject if http code 200
{"token":"itwbwKay7iUIOgT-GqnYeS_IXdjJi","user_id":17}
Or Error Json, describes exact error, if something went wrong
{"status":4,"description":"user provided token expired"}
How can I handle error status in response?
I tried this, but it doesn't see JSON in raw text (doens't work). And doesn't seems to be nice solution.
mCallLoginResponse.enqueue(new Callback<LoginResponce>() {
#Override
public void onResponse(Response<LoginResponce> response, Retrofit retrofit) {
if (response.isSuccess()) {
registerWithToken(response.body().getToken());
} else { //some error in responce
Gson gson = new GsonBuilder().create();
ApiError mApiError = gson.fromJson(response.raw().body().toString(),
ApiError.class); //Exception here - no JSON in String
//todo error handling
}
}
To get access to the response body when you have an error code, use errorBody() instead of body(). Also, there is a string method on ResponseBody that you should use instead of toString.
Gson gson = new GsonBuilder().create();
try {
ApiError mApiError = gson.fromJson(response.errorBody().string(),ApiError.class);
} catch (IOException e) {
// handle failure to read error
}