Android Java通过特殊字符分割字符串失败

时间:2019-10-05 13:46:57

标签: java android

如果URL没有查询字符串,我想用?将平台参数附加到URL,如果URL有查询字符串,我要使用&

所以我添加了以下内容

 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);
    }
}

即使网址中不包含urlParams,以上内容也始终将?评估为数组

网址示例

http://test.com

使用上面的代码解析为

http://test.com&platform=12

但是我希望它是http://test.com?platform=12

我尝试添加

String[] urlParams = this.api_url.split("?"); 

但是它会引发错误Dangling metacharacter。我在这方面错过了什么。为什么失败了?

1 个答案:

答案 0 :(得分:1)

这是error[E0499]: cannot borrow `*vec` as mutable more than once at a time 的预期行为。运行String#split返回一个包含一个元素"http://test.com".split("\\?")的数组。因此,只需将您的条件更新为"http://test.com"

您还可以考虑将String解析为Uri,因为您可能不需要此检查,而可以使用:

if(uriParams.length > 1)