2013-04-29 55 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