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
28 package org.apache.http.impl.conn;
29
30 import java.net.InetSocketAddress;
31 import java.net.Proxy;
32 import java.net.ProxySelector;
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.util.List;
36
37 import org.apache.http.HttpException;
38 import org.apache.http.HttpHost;
39 import org.apache.http.HttpRequest;
40 import org.apache.http.annotation.Contract;
41 import org.apache.http.annotation.ThreadingBehavior;
42 import org.apache.http.conn.SchemePortResolver;
43 import org.apache.http.protocol.HttpContext;
44
45
46
47
48
49
50
51
52
53 @Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL)
54 public class SystemDefaultRoutePlanner extends DefaultRoutePlanner {
55
56 private final ProxySelector proxySelector;
57
58
59
60
61 public SystemDefaultRoutePlanner(
62 final SchemePortResolver schemePortResolver,
63 final ProxySelector proxySelector) {
64 super(schemePortResolver);
65 this.proxySelector = proxySelector;
66 }
67
68
69
70
71 public SystemDefaultRoutePlanner(final ProxySelector proxySelector) {
72 this(null, proxySelector);
73 }
74
75 @Override
76 protected HttpHost determineProxy(
77 final HttpHost target,
78 final HttpRequest request,
79 final HttpContext context) throws HttpException {
80 final URI targetURI;
81 try {
82 targetURI = new URI(target.toURI());
83 } catch (final URISyntaxException ex) {
84 throw new HttpException("Cannot convert host to URI: " + target, ex);
85 }
86 ProxySelector proxySelectorInstance = this.proxySelector;
87 if (proxySelectorInstance == null) {
88 proxySelectorInstance = ProxySelector.getDefault();
89 }
90 if (proxySelectorInstance == null) {
91
92 return null;
93 }
94 final List<Proxy> proxies = proxySelectorInstance.select(targetURI);
95 final Proxy p = chooseProxy(proxies);
96 HttpHost result = null;
97 if (p.type() == Proxy.Type.HTTP) {
98
99 if (!(p.address() instanceof InetSocketAddress)) {
100 throw new HttpException("Unable to handle non-Inet proxy address: " + p.address());
101 }
102 final InetSocketAddress isa = (InetSocketAddress) p.address();
103
104 result = new HttpHost(getHost(isa), isa.getPort());
105 }
106
107 return result;
108 }
109
110 private String getHost(final InetSocketAddress isa) {
111
112
113
114
115 return isa.isUnresolved() ?
116 isa.getHostName() : isa.getAddress().getHostAddress();
117
118 }
119
120 private Proxy chooseProxy(final List<Proxy> proxies) {
121 Proxy result = null;
122
123 for (int i=0; (result == null) && (i < proxies.size()); i++) {
124 final Proxy p = proxies.get(i);
125 switch (p.type()) {
126
127 case DIRECT:
128 case HTTP:
129 result = p;
130 break;
131
132 case SOCKS:
133
134
135 break;
136 }
137 }
138 if (result == null) {
139
140
141
142 result = Proxy.NO_PROXY;
143 }
144 return result;
145 }
146
147 }