我的URI如下所示:
https://google.com.ua/oauth/authorize?client_id=SS&响应类型=代码&;范围=N_完整&;访问类型=离线&;重定向\u uri=http://localhost/Callback
我需要一个包含已解析元素的集合:
名称值
------------------------
客户识别码
响应类型代码
范围未满
脱机访问\u类型
重定向\u urihttp://localhost/Callback
确切地说,我需要一个C#/.NET的Java等价物HttpUtility.ParseQueryString方法
如果您正在寻找一种不使用外部库来实现它的方法,下面的代码将对您有所帮助
公共静态地图<;字符串,字符串>;splitQuery(URL)引发不支持的DencodingException{
Map<;String,String>;query_pairs=newlinkedhashmap<;String,String>;();
String query=url.getQuery();
String[]pairs=query.split(";);
for(字符串对:对){
int idx=pair.indexOf(";=";);
查询“u pairs.put(urldecker.decode(pair.substring(0,idx),”UTF-8“),urldecker.decode(pair.substring(idx+1),”UTF-8“);
}
返回查询对;
}
您可以使用访问返回的映射<;地图>;。获取(“客户id”),使用问题中给出的URL返回;SS"
更新添加URL解码
更新由于这个答案仍然很流行,我对上面的方法做了改进,它可以处理多个具有相同键的参数,也可以处理没有值的参数
公共静态地图<;字符串,列表<;字符串>&燃气轮机;splitQuery(URL)引发不支持的DencodingException{
最终映射<;字符串,列表<;字符串>;>;查询对=新LinkedHashMap<;字符串,列表<;字符串>;>;();
最终字符串[]对=url.getQuery().split(";);
for(字符串对:对){
final int idx=pair.indexOf(“=”);
最终字符串键=idx>;0?URLDecover.decode(成对子字符串(0,idx),“UTF-8”):成对;
如果(!query_pairs.containsKey(键)){
查询对.put(key,newlinkedlist<;String>;());
}
最终字符串值=idx>;0&;pair.length()>;idx+1?URLDecover.decode(pair.substring(idx+1),“UTF-8”):null;
查询对。获取(键)。添加(值);
}
返回查询对;
}
更新Java8版本
公共地图<;字符串,列表<;字符串>&燃气轮机;拆分查询(URL){
if(Strings.isNullOrEmpty(url.getQuery())){
return Collections.emptyMap();
}
返回Arrays.stream(url.getQuery().split(";))
.map(此::splitQueryParameter)
.collect(Collectors.groupingBy(simpleimutableentry::getKey,LinkedHashMap::new,mapping(Map.Entry::getValue,toList()));
}
公共SimpleMultiTableEntry<;字符串,字符串>;splitQueryParameter(字符串){
final int idx=it.indexOf(“=”);
最后一个字符串键=idx>;0?它。子字符串(0,idx):它;
最终字符串值=idx>;0&;it.length()>;idx+1?it.substring(idx+1):null;
返回新的SimpleMultiTableEntry<;>(
URLDecover.decode(键“UTF-8”),
URLDecover.decode(值“UTF-8”)
);
}
使用URL运行上述方法
https://stackoverflow.com?param1=value1&参数2=&;参数3=值3&;参数3
返回此映射:
{param1=[";value1";],param2=[null],param3=[";value3";,null]}