HttpURLConnection urlConn = (HttpURLConnection) new URL(
"http://www.google.com").openConnection();
InputStream is = urlConn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
result += inputLine;
}
说到urlConn.getInputStream(),它失败了。 但是相同的代码适用于普通的java项目而不是Android项目。
我发现在Android中,当它运行第一个语句时,urlConn是:" libcore.net.http.HttpURLConnectionImpl:http://www.google.com"
但是在普通的java项目中,它是" sun.net.www.protocol.http.HttpURLConnection:http://www.google.com"
谢谢!
异常堆栈:
11-21 21:14:01.750: I/System.out(20784): debugger has settled (1392)
11-21 21:14:56.380: W/dalvikvm(20784): threadid=1: thread exiting with uncaught exception (group=0x410e49d8)
11-21 21:14:56.420: E/AndroidRuntime(20784): FATAL EXCEPTION: main
11-21 21:14:56.420: E/AndroidRuntime(20784): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.network/com.example.network.MainActivity}: android.os.NetworkOnMainThreadException
11-21 21:14:56.420: E/AndroidRuntime(20784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1969)
11-21 21:14:56.420: E/AndroidRuntime(20784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1994)
11-21 21:14:56.420: E/AndroidRuntime(20784): at android.app.ActivityThread.access$600(ActivityThread.java:126)
我已添加INTERNET权限。
答案 0 :(得分:3)
那个着名的android.os.NetworkOnMainThreadException
:)
从 HoneyComb 开始,不允许在主(UI)线程上执行网络操作(默认情况下)。因此,请使用AsyncTask
或Thread
在单独的线程上执行此操作。
答案 1 :(得分:2)
不要在UT线程上进行联网(NetworkOnMainThreadException)。使用AsyncTask来避免此异常
有关详细信息,请参阅此文章:http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html