java servlet proxy

本文介绍了一个简单的HTTP代理服务实现,该服务支持GET和POST请求,并能够转发到指定URL。通过使用Apache Commons HttpClient库来处理HTTP请求,实现了基本的代理功能。
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;
        }
    }

}

Servlet Proxy是指一个Servlet可以将请求转发到另一个Web服务器上的Servlet,并将结果返回给客户端。实现Servlet Proxy的关键是使用Java的URLConnection类来发送HTTP请求并获取响应,然后将响应转发给客户端。 以下是一个简单的Servlet Proxy的实现示例: ```java public class ProxyServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("url"); if (url == null || url.isEmpty()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'url' parameter"); return; } HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); // 将请求头复制到连接中 Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement(); conn.setRequestProperty(header, request.getHeader(header)); } // 发送请求并获取响应 int status = conn.getResponseCode(); String contentType = conn.getContentType(); InputStream input = conn.getInputStream(); // 将响应头复制到响应中 response.setStatus(status); response.setContentType(contentType); for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) { if (header.getKey() != null && !header.getKey().equalsIgnoreCase("Content-Encoding")) { for (String value : header.getValue()) { response.addHeader(header.getKey(), value); } } } // 将响应体复制到响应中 OutputStream output = response.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } // 关闭连接和流 input.close(); output.close(); conn.disconnect(); } } ``` 上面的Servlet可以通过GET请求的url参数来指定要代理的URL。它使用Java的HttpURLConnection类发送HTTP请求,并将响应的头和主体复制到原始请求的响应中。注意,这种实现方法只支持GET请求,如果要支持POST请求,需要修改代码并添加必要的请求体。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值