2013-04-29 122 views
0

我有以下代碼連接到一個URL。我的問題是,當我在調試中運行它時,我看到connected = false以及我嘗試設置的其他參數都沒有工作(如timeout)。誰能幫我這個?我究竟做錯了什麼??android HttpsURLConnection未初始化

在任何人問起之前,我的清單已經有了互聯網許可。

private static class SyncOperation extends AsyncTask<String, String, Integer> { 

    @Override 
    protected Integer doInBackground(String... params) { 
     HttpsURLConnection urlConnection = null; 
     URL url = null; 
     String msg = "Good"; 
     int code = 0; 
     try { 
      System.setProperty("http.keepAlive", "false"); 
      url = new URL("https://www.google.com"); 
      urlConnection = (HttpsURLConnection) url.openConnection(); 
      urlConnection.setInstanceFollowRedirects(false); 
      urlConnection.setReadTimeout(10000 /* milliseconds */); 
      urlConnection.setConnectTimeout(15000 /* milliseconds */); 
      urlConnection.setRequestMethod("POST"); 
     } catch (MalformedURLException e) { 
      msg = "Bad MalformedURLException"; 
      e.printStackTrace(); 
      Log.e("HTTPS", e.getMessage()); 
     } catch (IOException e) { 
      msg = "Bad IOException"; 
      e.printStackTrace(); 
      Log.e("HTTPS", e.getMessage()); 
     } finally { 
      urlConnection.disconnect(); 
      Log.d("HTTPS", msg); 
      Log.d("HTTPS", "diconnected"); 
     } 

     return code; 
    } 

    @Override 
    protected void onPostExecute(Integer code) { 
     super.onPostExecute(code); 

     Toast t = Toast.makeText(mContext, code.toString(), Toast.LENGTH_SHORT); 
     t.show(); 

    } 

} 

回答

2

您只配置您的連接,但不連接它。方法url.openConnection()的名稱具有誤導性:它不打開連接。它只給你一個最初沒有連接的連接對象。

你需要調用任何這導致連接連接方法,例如connect()

換句話說,嘗試實際做一些與你的連接,喜歡閱讀的內容,將其寫入System.out.println()。這將自動打開連接。

+0

非常感謝!這是誤導... – Meir 2013-04-29 15:57:40