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 权限。