如何解决android使用HttpUrlConnection抛出异常

2025-05-16 06:33:55
推荐回答(1个)
回答(1):

Android中HttpURLConnection抛出异常的解决方法:
Http的URL链接, 会发生错误, 主要原因是 在主UI线程中, 使用网络调用(network call), 就抛出NetworkOnMainThreadException异常.
版本: API level 11以上.
可以使用一个简单的线程, 在后台(asynctask)调用程序, 可以避免此情况;
否则 在getResponseCode()函数处, 抛出异常.
Android API :
代码:
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();