1 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 53 public class ProxyRequestHandler implements HttpRequestHandler { 54 55 58 public boolean processRequest(SimpleHttpServerConnection conn) throws IOException { 59 RequestLine line = conn.getRequestLine(); 60 String method = line.getMethod(); 61 if (!"GET".equalsIgnoreCase(method)) return false; 63 URI url = new HttpURL(line.getUri()); 64 httpProxy(conn, url); 65 return true; 66 } 67 68 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 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 } 112 | Popular Tags |