RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Sep 26, 2005

Read a Web Page by Connecting to a Final Server Through a Proxy Server

This code uses the new J2SE 5.0 classes java.net.Proxy and java.net.Proxy.Type to connect to a final server through a proxy server in order to view a Web page. The Proxy class represents a proxy setting (proxy protocol and proxy address) and the Proxy.Type class represents the proxy type. This type can be:

DIRECT - no proxy;
HTTP - high level protocol such FTP,HTTP
SOCKS - SOCKS (V4 or V5)
In this example, the proxy type is HTTP and the proxy address is localhost, but it can be any other proxy. For opening a connection to that proxy, the code uses the openConnection(Proxy proxy) method of the URL class.

Before opening the connection, you must supply the URL that you want to access by replacing "the final server URL." The coonection is then made through the proxy server. The next step is to call the getInputStream method to read the Web page specified by the URL. After that, use BufferedReader to display the page content on the screen:

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

class read{ 

public read(){} 

BufferedReader buffer=null;      
String linie=null; 
URLConnection URLcon=null; 
URL url=null; 
InputStream IS=null; 

public void getURLContent() 
         try { 
             InetAddress addr=InetAddress.getLocalHost(); 
//or use getByName("proxy host");
             InetSocketAddress ISA=new InetSocketAddress(addr,port);
//where port is the proxy port 
             java.net.Proxy proxy=new java.net.Proxy(java.net.Proxy.Type.HTTP,ISA); 
//you may also use SOCKS or DIRECT types

                url=new URL("the final server URL");               
                URLcon = url.openConnection(proxy); 
                  buffer=new BufferedReader(new InputStreamReader(IS)); 
                              }                 buffer.close(); 
                    }catch(MalformedURLException e) 
                }catch(IOException e) 

public class ReadURLToProxy{ 
        public static void main(String[] args) 
        read t=new read(); 
Anghel Leonard
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date