HttpURLConnection fails on Android 4.0

一世执手 提交于 2019-12-19 20:47:18

问题


I am using this code to fetch my changelog from the net.

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 !
           }

This works, on Android 2.3 and below... But since the ICS update, i am getting nothing! No dialog, no response, no nothing! Help! :/


回答1:


I know in android 3.0 network connection on the main thread isnt permitted.

StrictMode is turned on automatically. Im sure it is the same for 4.0

To fix the issue, you must perform the network connection on a separate thread... for example, using an AsyncTask.


Read this blog post on the subject:

Why Ice Cream Sandwich Crashes Your App




回答2:


Well, why won't you use the WebClient? (usage: https://gist.github.com/2906703), you don't really need to mess up with the StrictMode Thread Policy. If google thought it was important to change it, who am I to disagree.



来源:https://stackoverflow.com/questions/8391420/httpurlconnection-fails-on-android-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!