当前位置: 代码迷 >> Android >> HttpUrlConnection请求网络数据错误有关问题
  详细解决方案

HttpUrlConnection请求网络数据错误有关问题

热度:74   发布时间:2016-04-27 22:46:08.0
HttpUrlConnection请求网络数据异常问题
public void getInputStream(){
new Thread(){
@Override
public void run() {
String path="http://m.weather.com.cn/atad/101010100.html";
try{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setConnectTimeout(5000);
con.setRequestMethod("GET");
if(con.getResponseCode()==200){
InputStream input=con.getInputStream();
Message msg=new Message();
msg.what=1;
msg.obj=input;
handler.sendMessage(msg);
}
}catch(Exception e){
Log.i("error","exception");
}
}
}.start();
}

这段程序,运行到if(con.getResponseCode()==200)这里就会出现异常,把if判断去掉后InputStream input=con.getInputStream();这句也会出现异常,我已经在配置文件中添加了权限,请问到底是哪里出了问题。

这是logcat
10-03 09:47:38.878: I/Choreographer(6447): Skipped 60 frames!  The application may be doing too much work on its main thread.
10-03 09:47:39.128: D/gralloc_goldfish(6447): Emulator without GPU emulation detected.
10-03 09:48:18.688: I/error(6447): exception

------解决思路----------------------

这样试试
new Thread(new Runnable() {
                        @Override
public void run() {

           }
}.start();





------解决思路----------------------
我看到后面有发送消息的代码?那你处理消息的代码在哪里??
------解决思路----------------------
在主线程中是可以有耗时操作的,访问网络属于耗时操作,如果主线程做大量耗时的事情的话就会有ANR异常。你将访问网络的操作放在子线程中执行,然后如果你有需求更新UI的话,只用Handler消息机制,将消息发送给Handler在主线程中执行更新UI的操作。记住。Activity的响应时间是5秒,service和BroadcastReceiver是10秒,超过时间就会报ANR异常。所以在主线程中是不可以有耗时操作的。
  相关解决方案