将字符串中的头数据转换为map< string,list< string>>

bkhjykvo  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(473)

我将http头数据作为字符串,如下所示。

{Accept=[*/*], accept-encoding=[gzip, deflate, br], cache-control=[no-cache], connection=[keep-alive], Content-Length=[273], content-type=[application/xml], host=[localhost:8090], SOAPAction=["http://someurl"]}

拆分依据 ',' 会导致不正确的拆分,因为值也是由 ',' . 我无法将此转换为 Map<String, List<String>> 或者 MultivaluedMap<String, String> .

holgip5t

holgip5t1#

假设值始终在
[ ] ,您可以使用非贪婪正则表达式来提取头及其值。然后,只需在 , 并将它们添加到 Map .

String input = "{Accept=[*/*], accept-encoding=[gzip, deflate, br], cache-control=[no-cache], connection=[keep-alive], Content-Length=[273], content-type=[application/xml], host=[localhost:8090], SOAPAction=[\"http://someurl\"]}";

Pattern pattern = Pattern.compile("([-\\w]+)=\\[(.*?)]");
Matcher matcher = pattern.matcher(input);

Map<String, List<String>> map = new HashMap<>();
while (matcher.find()) {
    String key = matcher.group(1);  // the header
    String val = matcher.group(2);  // its value

    map.put(key, Arrays.asList(val.split("\\s,\\s"))));
}

System.out.println(map);

输出:

{SOAPAction=["http://someurl"], Accept=[*/*], host=[localhost:8090], connection=[keep-alive], content-type=[application/xml], cache-control=[no-cache], Content-Length=[273], accept-encoding=[gzip, deflate, br]}

相关问题