Reputation: 6639
I would like to attach a platform parameter to a url with ?
if the url has no query string and using &
if url has a query string
SO i have added the following
String api_url;
//costructor next to assign apiurl value
//method to extract url and process request
processData(){
String apiUrl = "";
String[] urlParams = this.api_url.split("\\?");
if (urlParams.length > 0){
apiUrl = this.api_url+"&platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
}else {
apiUrl = this.api_url+"?platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
}
}
The above always evaluates the urlParams
to a an array even when a url doesnt contain the ?
Example for a url
http://test.com
is resolved with the above code as
http://test.com&platform=12
But i expected it to be as http://test.com?platform=12
I have tried adding
String[] urlParams = this.api_url.split("?");
But it throws an error of Dangling metacharacter
. What am i missing out on this. Why does this fail.
Upvotes: 0
Views: 77
Reputation: 8231
This is expected behaviour for String#split
. Running "http://test.com".split("\\?")
returns an array with one element, "http://test.com"
. So, just update your condition to if(uriParams.length > 1)
.
You could also consider parsing your String to a Uri, as you may not need this check and could possibly instead use:
Uri.parse(api_url)
.buildUpon()
.appendQuery("platform", tokenService.getToken(AppSettingsKeys.PLATFORM))
.build().toString();
Upvotes: 1