Android for Spring抛出null HttpClientErrorException

时间:2013-06-21 07:16:09

标签: android spring basic-authentication android-networking

我是SO和Android开发的新手。

首先,如果我的语法或拼写不正确,我道歉。我不是英语母语人士。

我正在尝试通过 Spring for Android 进行HTTP GET request。所有似乎都工作正常,直到我试图捕获发生错误(HttpClientErrorException)时抛出的异常,例如401(HTTP 401 UNAUTHORIZED)。

出于某种原因,Spring for Android会将此异常抛出为null

更明确一点,这是我的代码:

    protected Integer doInBackground(String... arg0) {
        String url = "http://192.168.0.105:8080/guniv/rest/test";

        String username = eTextUsername.getText().toString();
        String password = eTextPassword.getText().toString();

        // Setting Http BasicAuth headers
        HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAuthorization(authHeader);
        HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());


        // Doing request!!
        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            Log.i("INFO", response.getBody());
        } catch (HttpClientErrorException e) { // e is null!!
            String message = "";
            if( e.getStatusCode() == HttpStatus.UNAUTHORIZED ) 
                message = "Incorrect username or password.";

            //do something here...

        } 

        return 0; // TODO
    }

好吧,当发生一些HTTP错误并且HttpClientErrorException被捕获时,结果为null,显然e.getStatusCode()会引发NullPointerException

之前有人遇到过这个问题吗?

谢谢,再次抱歉我的英语!

0 个答案:

没有答案