我使用的是运行Express3.0的Node.js服务器。
在我的应用程序的一个部分中,我将json POST到一个URI,以在/api/transactions/powerup上购买通电。这有几个退货选项。
我将收到201表示交易有效,404表示由于资金不足,请求无效。我的问题是,如果我想只根据ResponseEntity中的头来告诉android客户端它是否成功。
没有返回给客户端的json,因为HTTP代码可以告诉我它是否成功。有人知道怎么做吗?
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似乎总是在Spring Android中抛出错误。无论如何,我可以简单地查看http标头,而不担心返回对象映射到吗?
RestTemplate
使用的DefaultResponseErrorHandler
为所有400和500系列HTTP状态响应抛出异常。一种选择是在RestTemplate请求中使用自定义ResponseErrorHandler
,该请求不会引发异常。您可以修改您的请求以使用自定义处理程序,然后检查预期的状态代码:
// 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
}
下面是一个不会抛出任何异常的"空"实现的示例:
class CustomErrorHandler implements ResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
}
因为服务器可能会返回其他状态代码,所以最好查找预期的状态代码,而不是为那些特定的状态代码抛出异常。但这只是取决于你的需求。此示例扩展了RestTemplate
使用的默认处理程序,并检查预期的状态代码:
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);
}
}
您肯定可以使用失败的异常吗?
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;
}