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

杰夫

我想将平台参数附加到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我在这方面错过了什么。为什么这失败了。

游击队

这是预期的行为String#split运行"http://test.com".split("\\?")返回一个包含一个元素的数组"http://test.com"因此,只需将您的条件更新为即可if(uriParams.length > 1)

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

Uri.parse(api_url)
    .buildUpon()
    .appendQuery("platform", tokenService.getToken(AppSettingsKeys.PLATFORM))
    .build().toString();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章