2

我是 SO 和 android 开发的新手。

首先,如果我的语法或拼写不正确,我深表歉意。我不是以英语为母语的人。

我正在尝试HTTP GET request通过Spring for Android做一个。一切似乎都正常,直到我尝试捕获发生错误时引发的异常 ( 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()throws NullPointerException

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

谢谢,再次为我的英语感到抱歉!

4

0 回答 0