Spring Android POST在ResponseEntity中没有返回类型application / octet-stream

时间:2013-02-22 08:04:17

标签: android spring post http-headers spring-annotations

我正在使用运行Express 3.0的Node.js服务器。

在我的应用程序的一个部分中,我将json发送到URI以在/ api / transactions / powerup上购买电源。这有几个返回选项。

我将收到201表示交易有效,404表示由于资金不足,请求无效。我的问题是,如果我想告诉Android客户端它是否成功只基于ResponseEntity中的标头。

没有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 ps似乎总是在Spring中抛出错误Android无论如何我只能看看http头而不用担心返回对象映射到?

2 个答案:

答案 0 :(得分:3)

DefaultResponseErrorHandler使用的

RestTemplate会引发所有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);
    }

}

答案 1 :(得分:0)

当然你可以将例外用作失败的吗?

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;
}