每当执行此代码时,应用程序就会崩溃并且不会返回任何数据。
我已经尝试过 Volley
和 okhttp
都没有成功。
val url = "https://..."
val lines = URL(url).openStream().use {
it.bufferedReader().readLines()
}
outputText.text = lines.toString()
我希望看到返回的信息,但应用程序崩溃了。
最佳答案
如果没有您的错误日志,我只能假设您遇到了 NetworkOnMainThreadException
异常。
如果是这样,您应该知道在 android 中您不能在主线程上运行与网络相关的操作 - 您需要在不同的线程上运行它们,例如:
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Put your code that you want to run in here.
} catch (Exception e) {
e.printStackTrace();
}
}
});
mThread.start
关于android - 只要发出此 HTTP 请求,应用程序就会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56655756/