Problem on remote hosts with HTTP client
I am writing a small HTTP client using sockets. The program accepts a remote host and port at the command line, sends it an HTTP GET request and returns its status code and the HTTP response. It displays the response.
It works on local addresses (localhost/127.0.0.1) but not on remote hosts such as www.google.com.
When I input:
http://localhost/test/index.html 8080
It works just fine for my local Jetty server. However, when I input:
http://www.google.com/search?q=Sathyaish 80
as the command line arguments, it gives me an UnknownHostException. Here's the stack trace:
Unknown host: www.google.com
java.net.UnknownHostException: www.google.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:153)
at java.net.Socket.connect(Socket.java:464)
at java.net.Socket.connect(Socket.java:414)
at java.net.Socket.<init>(Socket.java:310)
at java.net.Socket.<init>(Socket.java:125)
at NetworkClient.connect(GetURI.java:97)
at GetURI.main(GetURI.java:235)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)
Process finished with exit code 0
Here's my source code:
//package sathyaish.practice.network;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
class NetworkClient
{
private String _host =null;
private String _uri =null;
privateint _port = 0;
private String _requestGET;
privatestaticfinal String MSG_CONNECTING ="\nConnecting...";
public NetworkClient()
{
this("localhost","/", 8080);
}
public NetworkClient(String host, String uri,int port)
{
this.setHost(host);
this.setURI(uri);
this.setPort(port);
}
public String getHost()
{
return this._host;
}
publicvoid setHost(String host)
{
this._host = host;
this.resetGETRequest();
}
public String getURI()
{
return this._uri;
}
publicvoid setURI(String uri)
{
/* The uri can be null. */
if ( uri ==null )
uri ="/";
/* The uri can be an empty string like http://www.yahoo.com */
if ( uri =="" )
uri ="/";
/* The uri can be root: nothing to do here. Just let it be. */
/* The uri can be anything, with the whole path and the query string parameters etc. */
if ( uri.charAt(0) !='/')
uri ="/" + uri;
this._uri = uri;
this.resetGETRequest();
}
publicint getPort()
{
return this._port;
}
publicvoid setPort(int port)
{
this._port = port;
}
publicvoid setPort( String sPort )
{
try
{
int iPort = Integer.parseInt( sPort );
this.setPort ( iPort );
}
catch ( java.lang.NumberFormatException nfe )
{
System.out.println("Invalid port number: " + sPort );
System.exit ( 0 );
}
}
publicvoid resetGETRequest()
{
this._requestGET ="GET " + this._uri +" HTTP/1.1\nHost: " + this._host +"\n\n";
}
publicvoid connect()
{
try
{
Socket client =new Socket(this._host, this._port);
this.handleConnection(client);
}
catch (UnknownHostException uhe)
{
System.out.println("Unknown host: " + this._host);
uhe.printStackTrace();
}
catch (IOException ioe)
{
System.out.println("IO Exception occured: " + ioe.getMessage());
ioe.printStackTrace();
}
}
publicvoid handleConnection(Socket client)throws IOException
{
StringBuffer s =null;
String tmp =null;
try
{
PrintWriter out = SocketUtil.getPrintWriter(client);
if ( out !=null )
out.println(this._requestGET);
BufferedReader in = SocketUtil.getBufferedReader(client);
if ( in !=null )
{
s =new StringBuffer();
while( (tmp = in.readLine()) !=null )
s.append(tmp);
System.out.println("Connected to the server (" + this._host +":" + Integer.toString(this._port) +"). Sent the following request:\n");
System.out.print(this._requestGET);
System.out.println("\nResponse: " + s.toString());
}
if ( client !=null )
client.close();
}
catch (IOException ioe)
{
System.out.println("An exception occured: " + ioe.getMessage());
ioe.printStackTrace();
}
catch (Exception e)
{
System.out.println("An exception occured: " + e.getMessage());
e.printStackTrace();
}
}
}
class SocketUtil
{
publicstatic BufferedReader getBufferedReader(Socket client)throws IOException
{
returnnew BufferedReader(new InputStreamReader(client.getInputStream()));
}
publicstatic PrintWriter getPrintWriter(Socket client)throws IOException
{
returnnew PrintWriter(client.getOutputStream(),true);
}
}
class IOUtil
{
publicstatic String erase(String s)
{
if (s ==null)
return s;
int len = s.length();
StringBuffer sb =new StringBuffer(len);
for (int i = 0; i < len; i++)
sb.append('\b');
return sb.toString();
}
/* Assumes a space as the default delimiter */
publicstatic String join(String[] arr)
{
return IOUtil.join( arr," " );
}
publicstatic String join(String[] arr, String delimiter)
{
StringBuffer sb =new StringBuffer();
for (int i = 0; i < arr.length; sb.append (arr[i]), sb.append (delimiter), i++);
return sb.toString();
}
}
publicclass GetURIextends NetworkClient
{
public GetURI(String urlAndPort)
{
try
{
this.parse(urlAndPort);
}
catch (InvalidProtocolException ipe)
{
System.out.println(ipe.getMessage());
System.exit(0);
}
}
publicvoid parse(String urlAndPort)throws InvalidProtocolException
{
/* parse the URL and port here */
StringTokenizer t =new StringTokenizer(urlAndPort);
String protocol = t.nextToken(":/");
if ( !protocol.equals("http") )
thrownew InvalidProtocolException(protocol);
this.setHost( t.nextToken(":/") );
String tmp = t.nextToken(":");
if ( tmp.charAt(0) =='/' )
{
this.setURI( tmp );
this.setPort( t.nextToken().trim() );
}
else
this.setPort( tmp.trim() );
}
publicstaticvoid main(String[] args)
{
checkArgs(args);
GetURI g =new GetURI(IOUtil.join(args));
g.connect();
}
privatestaticvoid checkArgs(String[] args)
{
if ( args.length == 0 )
{
System.out.println("Usage: geturi uri[:port]");
System.exit(0);
}
}
}
class InvalidProtocolExceptionextends java.lang.Exception
{
public InvalidProtocolException(String protocol)
{
super("Invalid protocol: " + protocol);
}
}
Can someone please tell me if it works on their system and what's wrong with it?
Message was edited by:
Sathyaish

