一:基础介绍
- Android中的Uri与Java中的URI类
- 出现下列异常的原因是引用的链接存在空格,使用常用trim()方法来去空格。
java.lang.IllegalArgumentException: Illegal character in path at index 52: http://localhost:8080/xxxx/xxx/xxx.do
- 官方文档索引
二:示例代码
- 如果采用方法一:字符串处理
var url="http://qqq/book?id=1&name=烫烫烫"
val urlValue = url.substringAfter('?', "")
val urlParams = urlValue.split("&")
val urlParams = Bundle()
urlParams.forEach {
val param = it.split("=")
if (param.size == 2) {
urlParams.putString(param[0], param[1])
}
}
- 方法二 使用Uri拼接样例
fun getQueryKeyValueMap(uri: Uri): HashMap<String, String> {
val keyValueMap = HashMap<String, String>()
var key: String
var value: String
val keyNamesList = uri.queryParameterNames
val iterator = keyNamesList.iterator()
while (iterator.hasNext()) {
key = iterator.next() as String
value = uri.getQueryParameter(key) as String
keyValueMap.put(key, value)
}
return keyValueMap
}
2.5 例子
val paramBundle = Bundle()
var key: String
var value: String
val trackerStr = Uri.parse(deepLink.trim())
val keyNamesList = trackerStr.queryParameterNames
val iterator = keyNamesList.iterator()
while (iterator.hasNext()) {
key = iterator.next() as String
value = trackerStr.getQueryParameter(key) as String
paramBundle.putString(key, value)
}
进一步优化
- 声明可以放里面
- 强转可能会出问题,空指针异常。使用toString(kotlin)可解决。
2.1 若转换目标为null:空对象会变为"null" 2.2 若转换目标为"":其的意思是一个长度为0的字符串,转换后仍为""
val trackerStr = Uri.parse(deepLink)
if (trackerStr.toString().isEmpty()) return
val keyNamesList = trackerStr.queryParameterNames
val paramBundle = Bundle()
val iterator = keyNamesList.iterator()
while (iterator.hasNext()) {
val key = iterator.next()
val value = trackerStr.getQueryParameter(key).toString()
paramBundle.putString(key, value)
}
|