Reputation: 5111
I am working with a Node.js server running Express 3.0.
During one part in my application I POST json to a URI to purchase a powerup at /api/transactions/powerup. This has several return options.
I will either receive a 201 meaning that the transaction was valid, a 404 that the request was not valid due to insufficient funds. My problem is that if I want to tell the android client whether it was successful based only on the headers that are in the ResponseEntity.
There is no json that is passed back to the client because the HTTP codes can tell me if it was successful. Does anyone know how to do this?
PowerupPurchase purchase = new PowerupPurchase();
purchase.setPowerId(params[0]);
final String url = getString(R.string.external_api_url) + "/transactions/powers?apiKey="+mCurrentUser.getApiKey();
Log.i(TAG,url);
// create the headers
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
requestHeaders.setAcceptEncoding(ContentCodingType.GZIP);
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
// Create the Json that will be exchanged
HttpEntity<?> requestEntity = new HttpEntity<PowerupPurchase>(purchase, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
List<MediaType> mediaList = new LinkedList<MediaType>();
mediaList.add(new MediaType("application","octet-stream",Charset.forName("UTF-8")));
converter.setSupportedMediaTypes(mediaList);
restTemplate.getMessageConverters().add(converter);
try {
// Make the network request
ResponseEntity<?> response = restTemplate.postForEntity(url, requestEntity, Object.class);
// HOW DO I GET THE HEADERS??
response.getHeaders()
400's seem to always throw errors in Spring Android is there anyway that I can simply look at the http header and not worry about a return object map to?
Upvotes: 1
Views: 2105
Reputation: 2179
DefaultResponseErrorHandler
used by RestTemplate
throws exceptions for all 400 and 500 series HTTP Status responses. One option is to use a custom ResponseErrorHandler
with your RestTemplate request that won't throw exceptions. You can modify your request to use the custom handler and then check for the expected status codes:
// set the custom error handler
restTemplate.setErrorHandler(new CustomErrorHandler());
// make the request
ResponseEntity<Void> response = restTemplate.postForEntity(url, requestEntity, null);
// check status code
HttpStatus statusCode = response.getStatusCode();
if (statusCode == HttpStatus.CREATED) {
// handle success
} else if (statusCode == HttpStatus.NOT_FOUND) {
// handle error
}
Here is an example of an "empty" implementation that won't throw any exceptions:
class CustomErrorHandler implements ResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
}
Because the server might return other status codes, it's probably a good idea to look for the expected status codes and not throw exceptions for those particular ones. But it simply depends on what your needs are. This example extends the default handler used by RestTemplate
and checks for the expected status codes:
class CustomErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// check for expected status codes
if (isExpected(response.getStatusCode())) {
return;
}
super.handleError(response);
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
// check for expected status codes
if (isExpected(response.getStatusCode())) {
return false;
}
return super.hasError(response);
}
private boolean isExpected(HttpStatus statusCode) {
return (statusCode == HttpStatus.CREATED || statusCode == HttpStatus.NOT_FOUND);
}
}
Upvotes: 3
Reputation: 6409
Surely you can use the exception as failed?
boolean success;
try{
ResponseEntity<?> response = restTemplate.postForEntity(url, requestEntity, Object.class);
int result = response.getHeaders().getStatus()...
success = result >= 200 && result < 300;
}catch(Exception e){
success = false;
}
Upvotes: 0