java servlet proxy

来源:互联网 发布:class c语言 编辑:程序博客网 时间:2024/06/17 04:19
import java.io.IOException; import java.io.OutputStreamWriter;import java.net.URLDecoder; import java.util.Enumeration;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.HttpMethod;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.lang.NotImplementedException;public class SimpleProxy {    public final void proxyAjaxCall( String url,                                     HttpServletRequest request,                                     HttpServletResponse response) throws IOException {        // URL needs to be url decoded        url = URLDecoder.decode(url, "utf-8");        OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());        HttpClient client = new HttpClient();        try {            HttpMethod method = null;            // Split this according to the type of request            if (request.getMethod().equals("GET")) {                method = new GetMethod(url);            } else if (request.getMethod().equals("POST")) {                method = new PostMethod(url);                // Set any eventual parameters that came with our original // request (POST params, for instance)                Enumeration paramNames = request.getParameterNames();                while (paramNames.hasMoreElements()) {                    String paramName = paramNames.nextElement().toString();                    ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));                }            }else {                throw new NotImplementedException( "This proxy only supports GET and POST methods.");            }            // Execute the method            client.executeMethod(method);            // Set the content type, as it comes from the server            Header[] headers = method.getResponseHeaders();            for (Header header : headers) {                if ("Content-Type".equalsIgnoreCase(header.getName())) {                    response.setContentType(header.getValue());                }            }            // Write the body, flush and close            writer.write(method.getResponseBodyAsString());            writer.flush();            writer.close();        } catch (HttpException e) {            //log.error("Oops, something went wrong in the HTTP proxy", null, e);            writer.write(e.toString());            throw e;        } catch (IOException e) {            e.printStackTrace(); writer.write(e.toString()); throw e;        }    }}

0 0
原创粉丝点击