HttpUrlConnection is freezing my AsyncTask

2019-07-07 16:19发布

问题:

In the "doInBackground" function of a AsyncTask, I got the following piece of code :

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

When the credentials are ok, everything works fine and the ResponseCode is 200. But if I put the wrong credentials, getResponseCode() makes the AsyncTask wait for an answer indefinitely (timeout won't work). Looking at HttpUrlConnection object tells me that the ResponseCode is -1.

I need to handle every situation, even if the user provides a bad credential. How can I get an usable answer? Should I use another class than HttpUrlConnection?

回答1:

Are you returning String back from this function and are you handling exceptions? Did you write onPostExecute?

Here is the code that works perfectly for me:

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