Title

Tuesday, 20 January 2015

SimpleClient - GET request


I got this training task on my school which says: Make a change in "SimpleClient" so that it makes a GET request to a address given on the command line and stores the content of the response to a file on disk.

import java.net.*;  import java.io.*;    public class SimpleClient {   public static void main(String[] args) {   try {   Socket con = new Socket(args[0], Integer.parseInt(args[1]));     PrintStream out = new PrintStream(con.getOutputStream());   out.print(args[2]);   out.write(0); // mark end of message   out.flush();     InputStreamReader in = new InputStreamReader(con.getInputStream());   int c;   while ((c = in.read())!=-1)   System.out.print((char)c);     con.close();   } catch (IOException e) {   System.err.println(e);   }   }  }

As far as I can se the "con" instance of Socket should make a connection to a host (args[0] eg. www.google.com) through a port number (args[1]). Then a PrintStream "out" is made, but what is the function of out.print(args[2]) and out.write(0)? I do not understand the program completely so I would appreciate if someone could explain it to me and maybe tell what should be changed to make it work.

Opening a socket connection is not the same as firing a GET request. Have a look at How to use java.net.URLConnection to fire and handle HTTP requests?

No comments:

Post a Comment