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.protocol;
29
30 import java.io.IOException;
31 import java.net.InetAddress;
32
33 import org.apache.http.HttpConnection;
34 import org.apache.http.HttpException;
35 import org.apache.http.HttpHost;
36 import org.apache.http.HttpInetConnection;
37 import org.apache.http.HttpRequest;
38 import org.apache.http.HttpRequestInterceptor;
39 import org.apache.http.HttpVersion;
40 import org.apache.http.ProtocolVersion;
41 import org.apache.http.ProtocolException;
42 import org.apache.http.annotation.Immutable;
43
44
45
46
47
48
49
50 @Immutable
51 public class RequestTargetHost implements HttpRequestInterceptor {
52
53 public RequestTargetHost() {
54 super();
55 }
56
57 public void process(final HttpRequest request, final HttpContext context)
58 throws HttpException, IOException {
59 if (request == null) {
60 throw new IllegalArgumentException("HTTP request may not be null");
61 }
62 if (context == null) {
63 throw new IllegalArgumentException("HTTP context may not be null");
64 }
65
66 ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
67 String method = request.getRequestLine().getMethod();
68 if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) {
69 return;
70 }
71
72 if (!request.containsHeader(HTTP.TARGET_HOST)) {
73 HttpHost targethost = (HttpHost) context
74 .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
75 if (targethost == null) {
76 HttpConnection conn = (HttpConnection) context
77 .getAttribute(ExecutionContext.HTTP_CONNECTION);
78 if (conn instanceof HttpInetConnection) {
79
80
81 InetAddress address = ((HttpInetConnection) conn).getRemoteAddress();
82 int port = ((HttpInetConnection) conn).getRemotePort();
83 if (address != null) {
84 targethost = new HttpHost(address.getHostName(), port);
85 }
86 }
87 if (targethost == null) {
88 if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
89 return;
90 } else {
91 throw new ProtocolException("Target host missing");
92 }
93 }
94 }
95 request.addHeader(HTTP.TARGET_HOST, targethost.toHostString());
96 }
97 }
98
99 }