Android(安卓)- HttpURLConnection 抛出异常
16lz
2021-01-26
HttpURLConnection 抛出异常
本文地址:http://blog.csdn.net/caroline_wendy
Http的URL链接, 会发生错误, 主要原因是 在主UI线程中, 使用网络调用(network call), 就抛出NetworkOnMainThreadException异常.
版本: API level 11以上.
可以使用一个简单的线程, 在后台(asynctask)调用程序, 可以避免此情况;
否则 在getResponseCode()函数处, 抛出异常.
Android API :http://developer.android.com/reference/android/os/AsyncTask.html.
代码:
String quakeFeed = getString(R.string.quake_feed); url = new URL(quakeFeed); URLConnection connection; connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode();
修改:
Thread t = new Thread(new Runnable() { @Override public void run() { refreshEarthquakes(); } }); t.start();
即, 把需要网络调用(network call)的程序, 放入线程(thread)中执行.
更多相关文章
- Android(安卓)Handler的使用yu应该注意的问题
- 关于Service的使用
- android 使用InstanceState保存和恢复数据
- Android(安卓)4.0 ICS SystemUI浅析——StatusBar加载流程分析
- React Native安卓实现更新下载、安装
- Android中将View的内容保存为图像的方法
- Android之WebView和js交互-调用失败的看这里
- Android每隔几秒做一个动作实现方法
- Android(安卓)Audio stream type