Bypass Server Proxy with Java Code

Few days ago, i was writing Java Spider Web crawler that need to by pass by University proxy because of the firewall settings. Below here were the basic snippet code how we can bypass the proxy.

Java Library that needed :
import java.net.*;
import java.io.*;
import java.util.Properties;

Since we are using java property rather than compile with command as below :
UNIX
java -Dhttp.proxyHost=proxyhost
[-Dhttp.proxyPort=portNumber] URLReader

DOS shell (Windows 95/NT/XP)
java -Dhttp.proxyHost=proxyhost
[-Dhttp.proxyPort=portNumber] URLReader

Snipper Code :
//Place before you make a use of stream reader

Properties systemSettings = System.getProperties();
System.setProperty("http.proxySet", "true");

//Your proxy host server
systemSettings.put(“http.proxyHost”,”bluetongue.cs.rmit.edu.au”) ;

//Your proxy port
systemSettings.put(“http.proxyPort”, “8080”);

URL url = new URL(“http://www.google.com/news”);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

/* it’s not the greatest idea to use a sun.misc.* class
* Sun strongly advises not to use them since they can
* change or go away in a future release so beware.
*The username and password below ONLY be encoded that means
*it is not secure to transmit over the network. But since this is just a demo
*/

sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd =
encoder.encode("mydomain\\username:password".getBytes());
con.setRequestProperty
("Proxy-Authorization", "Basic " + encodedUserPwd);

That’s all, you should be able to compile and run now.

Advertisements

About Charles Ling
Web/Android/IPhone Developer. Very very interested in Web Architecture, Web Standard and and how to use Web to improve human social life and doing cool stuff.

One Response to Bypass Server Proxy with Java Code

  1. Simran says:

    It gives Exception in thread “main” java.io.IOException: Server returned HTTP response code: 504 for URL when i tried running the code.

    Pls give me the cause and solution to this problem.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: