HttpUrlConnection正在冻结我的AsyncTask

时间:2013-01-28 22:04:40

标签: java android http httpurlconnection

在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之外的其他类吗?

1 个答案:

答案 0 :(得分: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;
            }