Home > Blockchain >  java.net.MalformedURLException: no protocol: [Ljava.lang.String;@f2b1656 when trying to download fil
java.net.MalformedURLException: no protocol: [Ljava.lang.String;@f2b1656 when trying to download fil

Time:05-19

wanted to download a file from a website, json file from https://api.openrouteservice.org/ but i get this error: java.net.MalformedURLException: no protocol: [Ljava.lang.String;@f2b1656

here is the code

 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

creating the 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
    }

the url is working, i checked it in the browser

CodePudding user response:

Your problem is in the val urlString: String

Either you use a string interpolation to properly build the URL or you can use the Android approach using URI builder and the

appendPath(String)

appendQueryParameter(Param and Value).

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

CodePudding user response:

java.net.URLEncoder.encode(yourUrl).toString() will return:

https://api.openrouteservice.org/v2/directions/driving-car?api_key=5***&start=2,3&end=2,3java.net.MalformedURLException: no protocol: https://api.openrouteservice.org/v2/directions/driving-car?api_key=5***&start=2,3&end=2,3

I don't this that you need to cover your url with URLEncoder object. Just return your url and it will works.

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
}
  • Related