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