webview中使用HttpURLConnection解析url出错

knxw0001 2013-06-05 05:46:32
httpurlclient在android中是可以读到url表示的网页中的内容的,但是在webview中,使用就会出错,代码如下:

wv.loadUrl("http://www.baidu.com");
wv.setWebViewClient(new WebViewClient() {

@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
URL cumtURL;
try {
cumtURL = new URL(url);
URLConnection cumtConnection = cumtURL.openConnection();
DataInputStream din = new DataInputStream(cumtConnection
.getInputStream());
String inputLine;
while ((inputLine = din.readLine()) != null) {
System.out.println(inputLine);
}
din.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});


错误是:android.os.NetworkOnMainThreadException
请问为什么呢?
...全文
85 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Butterbean 2013-06-07
  • 打赏
  • 举报
回复
楼上正解 你的主线程的acitivity的onCreate函数中 增加如下判别 // TODO Auto-generated method stub String strVer=GetVersion.GetSystemVersion(); strVer=strVer.substring(0,3).trim(); float fv=Float.valueOf(strVer); if(fv>2.3) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O .penaltyLog() //打印logcat,当然也可以定位到dropbox,通过文件保存相应的log .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() //探测SQLite数据库操作 .penaltyLog() //打印logcat .penaltyDeath() .build()); } 给你应用放行 或者loadurl放到异步中
longer262110 2013-06-05
  • 打赏
  • 举报
回复
不能在主线程中进行网络访问操作,好像是4.0以后的限制

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧