0

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.

1
  • Why do you expect split to return nothing when the regex didn't match? Have you verified your claim? Also, why don't use just use contains? Commented Oct 5, 2019 at 13:52

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I had to add .buildUpon() on Uri.parse(api_url) otherwise .appendQuery shows an error. SO its Uri.parse(this.api_url) .buildUpon() .appendQueryParameter("platform", tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM)) .build().toString()
Sorry, I was working from memory - I've updated my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.