在Android 4.0连接HttpURLConnection失败

在Android 4.0连接HttpURLConnection失败

问题描述:

我使用以下代码从网络上获取changelog。

InputStream content = null;
           try {


               URL url = new URL("http://dreamhawk.blinkenshell.org/changelog.txt");
               HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
               urlConnection.setRequestMethod("GET");
               urlConnection.connect();

               content = urlConnection.getInputStream();


               BufferedReader r = new BufferedReader(new InputStreamReader(content));
               StringBuilder total = new StringBuilder();
               String line;
               String NL = System.getProperty("line.separator");
               try {
                   while ((line = r.readLine()) != null) {
                       total.append(line + NL);
                   }
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }

               String page = total.toString();

               Dialog dialog = new Dialog(Main.this);

               dialog.setContentView(R.layout.custom_dialog);
               dialog.setTitle(R.string.changelog);
               dialog.setCanceledOnTouchOutside(true);

               TextView text = (TextView) dialog.findViewById(R.id.text);
               text.setTextSize(13);
               text.setText(page);
               dialog.show();
           } catch (Exception e) {
               //handle the exception !
           }

在Android 2.3或以下版本可以正常运行。但是只要ICS更新,就没有dialog,没有response,什么都没有,怎么改变代码?求教。

在 android 3.0中,主线程的网络连接是不允许的。
StrictMode会自动打开。在 android 4.0也是一样的。
要修复这些问题,你必须在一个单独的线程中执行网络连接。例如,使用一个AsyncTask。

把e打印出来,不要吃掉,看看问题在哪里。