diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java index 1338148443..255e0b30f8 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java @@ -717,16 +717,7 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable { String forwardedToUse = StringUtils.tokenizeToStringArray(forwardedHeader, ",")[0]; Matcher matcher = FORWARDED_HOST_PATTERN.matcher(forwardedToUse); if (matcher.find()) { - String hostToUse = matcher.group(1).trim(); - int portSeparatorIdx = hostToUse.lastIndexOf(":"); - if (portSeparatorIdx > hostToUse.lastIndexOf("]")) { - host(hostToUse.substring(0, portSeparatorIdx)); - port(Integer.parseInt(hostToUse.substring(portSeparatorIdx + 1))); - } - else { - host(hostToUse); - port(null); - } + adaptForwardedHost(matcher.group(1).trim()); } matcher = FORWARDED_PROTO_PATTERN.matcher(forwardedToUse); if (matcher.find()) { @@ -736,16 +727,7 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable { else { String hostHeader = headers.getFirst("X-Forwarded-Host"); if (StringUtils.hasText(hostHeader)) { - String hostToUse = StringUtils.tokenizeToStringArray(hostHeader, ",")[0]; - int portSeparatorIdx = hostToUse.lastIndexOf(":"); - if (portSeparatorIdx > hostToUse.lastIndexOf("]")) { - host(hostToUse.substring(0, portSeparatorIdx)); - port(Integer.parseInt(hostToUse.substring(portSeparatorIdx + 1))); - } - else { - host(hostToUse); - port(null); - } + adaptForwardedHost(StringUtils.tokenizeToStringArray(hostHeader, ",")[0]); } String portHeader = headers.getFirst("X-Forwarded-Port"); @@ -767,6 +749,18 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable { return this; } + private void adaptForwardedHost(String hostToUse) { + int portSeparatorIdx = hostToUse.lastIndexOf(":"); + if (portSeparatorIdx > hostToUse.lastIndexOf("]")) { + host(hostToUse.substring(0, portSeparatorIdx)); + port(Integer.parseInt(hostToUse.substring(portSeparatorIdx + 1))); + } + else { + host(hostToUse); + port(null); + } + } + private void resetHierarchicalComponents() { this.userInfo = null; this.host = null;