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
29
30
31
32 package org.apache.commons.httpclient.server;
33
34 import java.io.IOException;
35 import java.io.InputStream;
36
37 import org.apache.commons.httpclient.Header;
38 import org.apache.commons.httpclient.HostConfiguration;
39 import org.apache.commons.httpclient.HttpClient;
40 import org.apache.commons.httpclient.HttpMethod;
41 import org.apache.commons.httpclient.HttpURL;
42 import org.apache.commons.httpclient.URI;
43 import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
44 import org.apache.commons.httpclient.methods.GetMethod;
45 import org.apache.commons.logging.Log;
46 import org.apache.commons.logging.LogFactory;
47
48 /***
49 * This request handler can handle GET and POST requests. It does
50 * nothing for all other request
51 * @author Ortwin Glueck
52 */
53 public class ProxyRequestHandler implements HttpRequestHandler {
54
55 /***
56 * @see org.apache.commons.httpclient.server.HttpRequestHandler#processRequest(org.apache.commons.httpclient.server.SimpleHttpServerConnection)
57 */
58 public boolean processRequest(SimpleHttpServerConnection conn) throws IOException {
59 RequestLine line = conn.getRequestLine();
60 String method = line.getMethod();
61
62 if (!"GET".equalsIgnoreCase(method)) return false;
63 URI url = new HttpURL(line.getUri());
64 httpProxy(conn, url);
65 return true;
66 }
67
68 /***
69 * @param conn
70 */
71 private void httpProxy(SimpleHttpServerConnection conn, URI url) throws IOException {
72 Log wireLog = LogFactory.getLog("httpclient.wire");
73
74 HttpClient client = new HttpClient();
75 HostConfiguration hc = new HostConfiguration();
76 hc.setHost(url);
77 client.setHostConfiguration(hc);
78
79
80 HttpMethod method = new GetMethod(url.getPathQuery());
81 Header[] headers = conn.getHeaders();
82 for (int i=0; i<headers.length; i++) {
83 method.addRequestHeader(headers[i]);
84 }
85 if (method instanceof EntityEnclosingMethod) {
86 EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
87 emethod.setRequestBody(conn.getInputStream());
88 }
89 client.executeMethod(method);
90
91
92 Header[] rheaders = method.getResponseHeaders();
93 InputStream targetIn = method.getResponseBodyAsStream();
94 ResponseWriter out = conn.getWriter();
95 out.println(method.getStatusLine().toString());
96 for (int i=0; i<rheaders.length; i++) {
97 out.print(rheaders[i].toExternalForm());
98 }
99 if (rheaders.length > 0) out.println();
100 out.flush();
101 out = null;
102 StreamProxy sp = new StreamProxy(targetIn, conn.getOutputStream());
103 sp.start();
104 try {
105 sp.block();
106 } catch (InterruptedException e) {
107 throw new IOException(e.toString());
108 }
109 }
110
111 }