无法连接到 URL 时如何处理 HttpURLConnection
How to treat HttpURLConnection when failed to connect to URL
当我的数据库是 运行 时,一切正常。但是什么时候不 运行 我的移动应用程序总是崩溃。
错误信息:
Caused by: java.net.ConnectException: Failed to connect to /httpURL.
如何解决问题?
这是我的代码:
AsyncTaskHandleJson().execute(url)
inner class AsyncTaskHandleJson : AsyncTask<String, String, String>() {
override fun doInBackground(vararg url: String?): String {
var text: String
var connection = URL(url[0]).openConnection() as HttpURLConnection
try {
connection.connect()
text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
} finally {
connection.disconnect()
}
return text
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
}
}
由于您的代码中没有 catch
块,您目前没有捕获任何异常。
如果您想处理 ConnectException
,那么您只需抓住它:
override fun doInBackground(vararg url: String?): String {
var text = ""
var connection: HttpURLConnection? = null
try {
connection = URL(url[0]).openConnection() as HttpURLConnection
connection.connect()
text = connection.inputStream.use {
it.reader().use { reader ->
reader.readText()
}
}
} catch (ce: ConnectException) {
// ConnectionException occurred, do whatever you'd like
ce.printStackTrace()
} catch (e: Exception) {
// some other Exception occurred
e.printStackTrace()
} finally {
connection?.disconnect()
}
return text
}
当我的数据库是 运行 时,一切正常。但是什么时候不 运行 我的移动应用程序总是崩溃。
错误信息:
Caused by: java.net.ConnectException: Failed to connect to /httpURL.
如何解决问题?
这是我的代码:
AsyncTaskHandleJson().execute(url)
inner class AsyncTaskHandleJson : AsyncTask<String, String, String>() {
override fun doInBackground(vararg url: String?): String {
var text: String
var connection = URL(url[0]).openConnection() as HttpURLConnection
try {
connection.connect()
text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
} finally {
connection.disconnect()
}
return text
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
}
}
由于您的代码中没有 catch
块,您目前没有捕获任何异常。
如果您想处理 ConnectException
,那么您只需抓住它:
override fun doInBackground(vararg url: String?): String {
var text = ""
var connection: HttpURLConnection? = null
try {
connection = URL(url[0]).openConnection() as HttpURLConnection
connection.connect()
text = connection.inputStream.use {
it.reader().use { reader ->
reader.readText()
}
}
} catch (ce: ConnectException) {
// ConnectionException occurred, do whatever you'd like
ce.printStackTrace()
} catch (e: Exception) {
// some other Exception occurred
e.printStackTrace()
} finally {
connection?.disconnect()
}
return text
}