Creating proxy in Java PDF Print E-mail
Programming - java

The modern browsers do not allow the client side codes like javascript to access other servers from the client side which is known as "Same Origin Policy". The technologies like AJAX whose heart lies on the Javascript, can not access any other server except the same server on which it is hosted on. This policy do not allow even a different port number to be accessed by a webpage on the same host. There has been a lot of talks about the "JSON" technology instead of the universal "XML" technology to be used, but at the moment most of the communication takes place through XML document. For XML communication to happen and the web-services to be accessed, we need to create a proxy server on the same host, which will send the XML request to the "External Server" on the behalf of the AJAX client.

The following code will do the job. just host the code as a servlet and send the XML request to the proxy servlet.

 

The request to the proxyServlet must have a header ServerAddress set to the final destination of the request.

 

 

Source Code
package package.server;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProxyServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * This function handles the HTTP/GET requests 
     * @param req request received from client
     * @param resp request to be send to the client 
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String RequesttoExternalServer;
        String targetServer = req.getHeader("ServerAddress");

        InputStream in = req.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        ServletOutputStream out;
        String line;
        StringBuffer sb = new StringBuffer();
        // Receives the request from calling procedure
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        RequesttoExternalServer = sb.toString();

        // Send the request to external server
        URL url = new URL(targetServer);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(RequesttoExternalServer);
        wr.flush();

        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String ResponseFromExternalServer;
        sb = new StringBuffer();

        // Get the response from external Server
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        ResponseFromExternalServer = sb.toString();

        // Send back the response received to calling proc
        out = resp.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        resp.setHeader("Content-type", "text/xml");
        resp.setContentType("text/xml");
        for (int i = 0; i < ResponseFromExternalServer.length(); i++)
            bos.write(ResponseFromExternalServer.charAt(i));
        bos.flush();
    }

    /**
     * This function handles the HTTP/POST requests 
     * @param req request received from client
     * @param resp request to be send to the client 
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Enumeration params = req.getParameterNames();
        String targetServer = req.getHeader("ServerAddress") + "?";

        for (; params.hasMoreElements();) {
            String name = (String) params.nextElement();
            String value = req.getParameter(name);
            targetServer += name + "=" + value + "&";
        }
        targetServer = targetServer.substring(0, targetServer.length() - 1);
        // send the request to the external server
        URL url = new URL(targetServer);
        URLConnection conn = url.openConnection();

        // Receive the response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn
                .getInputStream()));
        String ResponseFromExternalServer;
        StringBuffer sb = new StringBuffer();
        String line;

        // Get the response from external Server
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        ResponseFromExternalServer = sb.toString();

        // Send the response back to calling function
        ServletOutputStream out;
        out = resp.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        resp.setHeader("Content-type", "text/xml");
        resp.setContentType("text/xml");
        for (int i = 0; i < ResponseFromExternalServer.length(); i++)
            bos.write(ResponseFromExternalServer.charAt(i));
        bos.flush();
    }

}

Last Updated on Sunday, 28 March 2010 07:24