Android 4.0上的HttpURLConnection失败

Dre*_*awk 4 android httpurlconnection

我正在使用此代码从网上获取我的更改日志.

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 !
           }
Run Code Online (Sandbox Code Playgroud)

这适用于Android 2.3及以下......但自从ICS更新后,我什么都没得到!没有对话,没有回应,没有任何东西!救命!:/

cod*_*e22 15

我知道在android 3.0网络连接上主线程是不允许的.

StrictMode自动打开.我确定4.0是相同的

要解决此问题,您必须在单独的线程上执行网络连接...例如,使用AsyncTask.


阅读此主题的博客文章:

为什么冰淇淋三明治崩溃你的应用程序

  • 请不要只是禁用严格模式.严格模式告诉你一些事情.在UI-Thread上进行网络呼叫将导致您的应用和整个手机冻结.您的网络是否在异步任务中调用 (5认同)