想从网站下载一个文件,从https://api.openrouteservice.org/下载json文件,但我得到了以下错误: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正在工作,我在浏览器中检查了它。
发布于 2022-05-18 16:11:27
您的问题在val urlString: String中。
可以使用字符串内插来正确构建URL,也可以使用Android方法使用URI生成器和
appendPath(字符串)
appendQueryParameter(Param and Value)。
https://developer.android.com/reference/android/net/Uri.Builder
发布于 2022-05-18 16:16:03
java.net.URLEncoder.encode(yourUrl).toString()将返回:
https%3A%2F%2Fapi.openrouteservice.org%2Fv2%2Fdirections%2Fdriving-car%3Fapi_key%3D5***%26start%3D2%2C3%26end%3D2%2C3java.net.MalformedURLException:无协议: https%3A%2F%2Fapi.openrouteservice.org%2Fv2%2Fdirections%2Fdriving-car%3Fapi_key%3D5***%26start%3D2%2C3%26end%3D2%2C3
我并不是说您需要用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
}https://stackoverflow.com/questions/72292312
复制相似问题