ssummeraw 2012-12-26 07:21 采纳率: 10%
浏览 7238
已采纳

在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,什么都没有,怎么改变代码?求教。

  • 写回答

2条回答

  • yongyong_21 2012-12-26 09:45
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程