从 URL 中提取查询值 [英] Extract query value from URL

查看:49
本文介绍了从 URL 中提取查询值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下网址:https://play.google.com/store/apps/details?id=eu.bandainamcoent.verylittlenightmares&hl=en";

我想提取这个值:eu.bandainamcoent.verylittlenightmares

URI uri = new URI(URL);
uri.getQuery();

我会得到这个:id=eu.bandainamcoent.verylittlenightmares&hl=en

如何截取id=&hl=en?而 &hl=en 可能不存在并且可以不同,例如 &hl=de 等.

How to cut id= and &hl=en? And &hl=en may not exist and can be different, like &hl=de etc.

推荐答案

URI 中没有函数可以做到这一点,但这里有一个解决方案:

There are no function in URI to do this, but here is a trick to solve it:

Map<String, String> params = Arrays.stream(uri.getQuery().split("&"))
        .map(s -> s.split("="))
        .collect(Collectors.toMap(k -> k[0], v -> v.length > 1 ? v[1] : ""));
String id = params.get("id"); // eu.bandainamcoent.verylittlenightmares
String hl = params.get("hl"); // en

我们确定两个参数之间唯一的分隔符是&,并且参数的名称和值由=分隔,因此您用分隔>&,并且对于每个结果用 = 分割,结果是一个 Map,其中包含参数名称作为键和值作为值.

We are sure that the only separator between two parameters is &, and the parameter have a name and value separated by =, for that you split with &, and for each result split with =, and the result is a Map which contain the param name as key and value as value.

这篇关于从 URL 中提取查询值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆