英文:
Convert Headers data in String to Map<String, List<String>>
问题
我将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>
。
英文:
I have the HTTP headers data as a String as below.
{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"]}
Splitting based on ','
leads to incorrect splitting as the values are also separated by ','
. I am not able to convert this to a Map<String, List<String>>
or MultivaluedMap<String, String>
.
答案1
得分: 1
假设这些值始终在 [
]
内,您可以使用非贪婪正则表达式来提取标题及其值。然后,只需在逗号处分割值,并将它们添加到您的 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']}
英文:
Assuming the values are always within [
]
, you can use a non-greedy regex to extract the headers and their values. Then, just split the values at ,
and add them to your 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);
Output:
{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]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论