skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. java.net.URLEncoder.encode(yourUrl).toString() will return:

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

    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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search