Question

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.

Was it helpful?

Solution 2

Okay, I found a solution if anyone should be interested.

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

public class SimpleClient {
    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter(args[args.length - 1]);

            BufferedWriter bw = new BufferedWriter(fw);
            try {
                Socket con = new Socket(args[0], Integer.parseInt(args[1]));

                PrintStream out = new PrintStream(con.getOutputStream());
                out.println("GET /search?q=" + args[2] + " HTTP/1.1");
                out.println("Host: www.google.com");
                out.println("");
                out.write(0); // mark end of message
                out.flush();

                InputStreamReader in = new InputStreamReader(
                        con.getInputStream());
                int c;
                while ((c = in.read()) != -1)
                    bw.write((char) c);    
                con.close();
            } catch (IOException e) {
                System.err.println(e);
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top