2

在 AsyncTask 的“doInBackground”函数中,我得到了以下代码:

try 
{ 
    URL url = new URL(myUrl);       
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);  



    Authenticator.setDefault(new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication() {                                              

        return new PasswordAuthentication ("myUsername", "myPassword".toCharArray());
        }           
    });

    conn.connect();
    int response = conn.getResponseCode();
    inputStream = conn.getInputStream();
    String content = convertInputStreamToString(inputStream);

    return content;

catch (Exception e) {
    e.printStackTrace();
    return null;            
}

当凭据正常时,一切正常并且 ResponseCode 为 200。但如果我输入了错误的凭据,getResponseCode() 会使 AsyncTask 无限期地等待答案(超时不起作用)。查看 HttpUrlConnection 对象告诉我 ResponseCode 是-1。

即使用户提供了错误的凭据,我也需要处理所有情况。我怎样才能得到一个有用的答案?我应该使用 HttpUrlConnection 以外的其他类吗?

4

1 回答 1

4

您是否String从该函数返回并处理异常?你写了onPostExecute吗?

这是非常适合我的代码:

        URL url = new URL(strUrl);  

            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Host", "myhost.com");
            conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
            conn.setRequestProperty("Accept-Charset", "UTF-8");

            conn.setConnectTimeout (5000) ; 
            conn.setDoOutput(true); 
            conn.setDoInput(true); 

            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            result = Utilities.readStream(in);

            status_code = conn.getResponseCode();

            return result;  
        } catch (MalformedURLException e) {
            return e.getMessage();
          } catch (ProtocolException e) {

                try {
                    status_code = conn.getResponseCode();
                } catch (IOException e1) {
                    status_code = -1;
                }


              return e.getMessage();
          } catch (IOException e) {
                try {
                    status_code = conn.getResponseCode();
                } catch (IOException e1) {
                    status_code = -1;
                }

              return e.getMessage();
          } catch ( Exception e ) {
                try {
                    status_code = conn.getResponseCode();
                } catch (IOException e1) {
                    status_code = -1;
                }
              return e.getMessage();
          } 
            finally
            {
                conn = null;
            }
于 2013-01-28T22:41:10.723 回答