HttpURLConnection connection = null;
InputStream istream = null; //input to proxy
OutputStream ostream = null; //output from proxy
InputStream connectionIstream = null; //output for the target is input for the connection
OutputStream connectionOstream = null; //input for the target is output for the connection
String remoteHost = request.getRemoteHost(); // get host address of client - for checking allowedHosts
boolean allowedHost = isAllowedHost(remoteHost); //The allowedHosts are the hosts that are allowed to use the Open Proxy.
try {
// easy way to ignore case of param?
if(request.getParameter("targetURL") != null && request.getParameter("targetURL") != "" && allowedHost) {
// HTTPUrlConnection looks at http.proxyHost and http.proxyPort system properties.
// Make sure these properties are set these if you are behind a proxy.
//step 1: initialize
String requestMethod = request.getMethod();
URL targetURL = new URL(request.getParameter("targetURL"));
connection = (HttpURLConnection) targetURL.openConnection();
connection.setRequestMethod(requestMethod);
transferHTTPRequestHeaders(connection, request);
//step 2: proxy requests
if (requestMethod.equals("GET")){
//default for setDoInput is true
connectionIstream = connection.getInputStream();
};
if (requestMethod.equals("POST")){
transferHTTPRequestHeadersForPOST(connection, request);
int clength = request.getContentLength();//clength is for checking if there is a POST body. Is that sufficient?
if(clength > 0) {
istream = request.getInputStream();
connection.setDoOutput(true);//for POST we need to write to connection
connection.setRequestProperty( "Content-Length",Integer.toString(clength)); //only valid for POST request
connectionOstream = connection.getOutputStream();
//copy the request body to remote outputStream
copy(istream, connectionOstream);
}
connectionIstream = connection.getInputStream();
}