1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.routing;
28
29 import java.net.URI;
30 import java.net.URISyntaxException;
31
32 import org.apache.hc.client5.http.SchemePortResolver;
33 import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
34 import org.apache.hc.client5.http.utils.URIUtils;
35 import org.apache.hc.core5.http.HttpException;
36 import org.apache.hc.core5.http.HttpHost;
37 import org.apache.hc.core5.http.HttpRequest;
38 import org.apache.hc.core5.http.ProtocolException;
39 import org.apache.hc.core5.net.URIAuthority;
40
41 public final class RoutingSupport {
42
43 public static HttpHost determineHost(final HttpRequest request) throws HttpException {
44 if (request == null) {
45 return null;
46 }
47 final URIAuthority authority = request.getAuthority();
48 if (authority != null) {
49 final String scheme = request.getScheme();
50 if (scheme == null) {
51 throw new ProtocolException("Protocol scheme is not specified");
52 }
53 return new HttpHost(scheme, authority);
54 }
55 try {
56 final URI requestURI = request.getUri();
57 if (requestURI.isAbsolute()) {
58 final HttpHost httpHost = URIUtils.extractHost(requestURI);
59 if (httpHost == null) {
60 throw new ProtocolException("URI does not specify a valid host name: " + requestURI);
61 }
62 return httpHost;
63 }
64 } catch (final URISyntaxException ignore) {
65 }
66 return null;
67 }
68
69 public static HttpHost normalize(final HttpHost host, final SchemePortResolver schemePortResolver) {
70 if (host == null) {
71 return null;
72 }
73 if (host.getPort() < 0) {
74 final int port = (schemePortResolver != null ? schemePortResolver: DefaultSchemePortResolver.INSTANCE).resolve(host);
75 if (port > 0) {
76 return new HttpHost(host.getSchemeName(), host.getAddress(), host.getHostName(), port);
77 }
78 }
79 return host;
80 }
81
82 }