Search code examples
androidjsonstringurluribuilder

URI Builder result has an unexpected colon in it (Android Programming)


For Uri.Builder, I'm using scheme(String) and building a URL string from there. However, within my final String there is a colon symbol : which changes the results from the query. Here is my code.

 Uri.Builder toBuild = new Uri.Builder();
        final String baseURL = "http://api.openweathermap.org/data/2.5/forecast/daily";

        toBuild.scheme(baseURL)
                .appendQueryParameter("zip", postal_Code[0])
                .appendQueryParameter("mode", "json")
                .appendQueryParameter("units", "metric")
                .appendQueryParameter("cnt", "7");

        String formURL = toBuild.toString();
        Log.v(LOG_TAG, "Formed URL: " + formURL);

My resulting String should have been http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043&mode=json&units=metric&cnt=7

but instead ended like http://api.openweathermap.org/data/2.5/forecast/daily:?zip=94043&mode=json&units=metric&cnt=7

with the colon appearing after the daily from the baseURL String. Please advise on how to remove the colon from the String. Thanks.


Solution

  • The ":" is coming because you are setting the baseUrl using the scheme which is supposed to be ("http", "https" etc) and in a url scheme is always followed by a colon so that is why u see the extra colon.

    I would build this URL part by part like this:

        Uri.Builder builder = new Uri.Builder();
        builder.scheme("http")
                .authority("api.openweathermap.org")
                .appendPath("data")
                .appendPath("2.5")
                .appendPath("forecast")
                .appendPath("daily")
                .appendQueryParameter("zip", "94043")
                .appendQueryParameter("mode", "json")
                .appendQueryParameter("units", "metric")
                .appendQueryParameter("cnt", "7");
    String formURL = builder.toString();
    

    result: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043&mode=json&units=metric&cnt=7