java.net.MalformedURLException: no protocol: [Ljava.lang.Str



想从一个网站下载一个文件,json文件从https://api.openrouteservice.org/但我得到这个错误:java.net.MalformedURLException: no protocol: [Ljava.lang.String;@f2b1656

代码

private fun downloadUrl(strUrl: String): String{
var fullData = ""
try {
URL(strUrl).openStream().use { inp ->
BufferedInputStream(inp).use { bis ->
val data = ByteArray(1024)
var count: Int
while (bis.read(data, 0, 1024).also { count = it } != -1) {
fullData += data.toString()
}
}
}
}catch (e: Exception){
Log.d("DownloadTask", e.toString())
}
return fullData

创建url

private fun getDirectionURL(): String{
val destination: String = coordinates[2].toString() + "," + coordinates[3].toString()
val origin: String = globalLocation.longitude.toString() + "," + globalLocation.latitude.toString()
val urlString: String = java.net.URLEncoder.encode("https://api.openrouteservice.org/v2/directions/driving-car?api_key=5***&start=" + origin + "&end=" + destination, "UTF-8")
Log.d("urlCreate", urlString)
return urlString
}

url是工作的,我检查了它在浏览器

你的问题在val url: String

你可以使用字符串插值来正确构建URL,或者你可以使用Android方法使用URI构建器和

appendPath(字符串)

appendQueryParameter(Param and Value).

https://developer.android.com/reference/android/net/Uri.Builder

java.net.URLEncoder.encode(yourUrl).toString()将返回:

https%3A%2F%2Fapi.openrouteservice.org%2Fv2%2Fdirections%2Fdriving-car%3Fapi_key%3D5***%26start%3D2%2C3%26end%3D2% 3D2% 2c3java.net . malformmedurlexception: no protocol: https%3A%2F%2Fapi.openrouteservice.org%2Fv2%2Fdirections%2Fdriving-car%3Fapi_key%3D5***%26start%3D2%2C3%26end%3D2%2C3

我不认为你需要覆盖你的url与URLEncoder对象。只要返回你的url,它就会工作。

private fun getDirectionURL(): String{
val destination: String = coordinates[2].toString() + "," + coordinates[3].toString()
val origin: String = globalLocation.longitude.toString() + "," + globalLocation.latitude.toString()
val urlString: String = "https://api.openrouteservice.org/v2/directions/driving-car?api_key=5***&start=$origin&end=$destination"
Log.d("urlCreate", urlString)
return urlString
}

相关内容

最新更新