HttpUrlConnection请求网络数据异常原因

Android 码拜 9年前 (2015-10-10) 1406次浏览
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

解决方案:15分

这样试试

new Thread(new Runnable() {

                        @Override

public void run() {

           }

}.start();

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

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明HttpUrlConnection请求网络数据异常原因
喜欢 (0)
[1034331897@qq.com]
分享 (0)