假设我有一个 url,我尝试获取重定向的 url。我使用了以下代码:
useEffect(() => {
const getAlbumCollection = async () => {
try {
const response = await axios({
url: "http://localhost:5000/api/albums",
method: "get",
data: {
userId: isAuth.id,
},
});
console.log(response);
} catch (error) {
console.log(error.message);
}
};
getAlbumCollection();
}, []);
即使在 java 编译器中似乎可以工作,我在 android 中也会出现以下错误(从 logcat 复制粘贴)。
fun getRedirectUrl(url: String?): String? {
var urlTmp: URL? = null
var redUrl: String? = null
var connection: HttpURLConnection? = null
try {
urlTmp = URL(url)
} catch (e1: MalformedURLException) {
e1.printStackTrace()
}
try {
connection = urlTmp!!.openConnection() as HttpURLConnection
} catch (e: IOException) {
e.printStackTrace()
}
try {
connection!!.responseCode
} catch (e: IOException) {
e.printStackTrace()
}
redUrl = connection!!.url.toString()
connection.disconnect()
return redUrl
}
我也知道这个 post。为什么会发生这种情况?有什么想法吗?
答案 0 :(得分:0)
问题是我不应该在主线程上运行这样的代码。使用 AsyncTask 解决了这个问题。示例
private class getRedirectUrl(url:String) : AsyncTask<String?, Int?, String>() {
val url = url
override fun doInBackground(vararg p0: String?): String {
var urlTmp: URL? = null
var redUrl: String? = null
var connection: HttpURLConnection? = null
try {
urlTmp = URL(url)
} catch (e1: MalformedURLException) {
e1.printStackTrace()
}
try {
connection = urlTmp!!.openConnection() as HttpURLConnection
} catch (e: IOException) {
e.printStackTrace()
}
try {
connection!!.responseCode
} catch (e: IOException) {
e.printStackTrace()
}
redUrl = connection!!.url.toString()
connection.disconnect()
return redUrl
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
Log.d("Redirected URL",""+result)
}
}
现在您可以使用
获取重定向的网址 getRedirectUrl("the url you want to get redirect").execute()