Set proxy in java for firewall

Posted By: Matpal Media - 7:01 AM

Sometimes you find difficult to access or read any internet URL from your JAVA code. Your corporate firewall or other firewall stops you in doing this because of security reasons. Tou find that your code is fine but showing  following exception-
java.net.UnknownHostException
You can avoid this exception by adding just a simple code snippet in your existing code. The snippet is nothing but the proxy setting for your network. You have to add follwing lines in your code.

System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "proxyHost", "<your proxy host ip>");
System.getProperties().put( "proxyPort", "80");

The complete example is-


import java.io.*;
import java.net.*;

public class proxyHost 
{
public static void main(String args[])
{
try
{
System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "proxyHost", "<your proxy host ip>");
System.getProperties().put( "proxyPort", "80");

URL myURL = new URL("http://google.com");
URLConnection conn = myURL.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null) 
System.out.println(inputLine);
in.close();
 
}
catch(Exception e)
{
e.printStackTrace();
}

}
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.