【问题标题】:Convert Headers data in String to Map<String, List<String>>将 String 中的 Headers 数据转换为 Map<String, List<String>>
【发布时间】:2020-08-19 18:38:26
【问题描述】:

我将 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&lt;String, List&lt;String&gt;&gt; 或 MultivaluedMap&lt;String, String&gt;。

【问题讨论】:

  • 您在哪里/在什么情况下获得这些标头?
  • 扩展 Apache CXF LoggingInInterceptor 以这种格式返回标头。
  • 那个已经被弃用一年多了?
  • 另外,这似乎不正确; the interface says it's a Map,您似乎只是在打印toString(),而不是调用get(ACCEPT_ENCODING)
  • @chrylis-cautiouslyoptimistic- 是的,就是这样。我在 loggingMessage 上调用方法 getHeader 并得到该值。

标签: java http-headers


【解决方案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]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2016-07-21
    • 2021-12-21
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2019-09-10
    • 2018-09-06
    相关资源
    最近更新 更多