android-studio - java.net.MalformedURLException:无协议:[Ljava.lang.String;@f2b1656 尝试在 kotlin 中下载文件时

想从网站下载文件,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

创建网址

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
    }

网址有效,我在浏览器中检查了它

回答1

您的问题出在 val urlString: String

您可以使用字符串插值来正确构建 URL,也可以使用 Android 方法使用 URI builder 和

附加路径(字符串)

追加查询参数(参数和 Value)。

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

回答2

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
}

相似文章