Advertisement
Guest User

Untitled

a guest
Mar 4th, 2015
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.31 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.ArrayList;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. /*
  8. * A simple HTTP Client application
  9. *
  10. * Computer Networks, KU Leuven.
  11. *
  12. * Arne De Brabandere
  13. * Ward Schodts
  14. */
  15. class HTTPClient {
  16.  
  17.     /**
  18.      * Log file: log.txt
  19.      */
  20.     public static LogFile logFile = new LogFile("log.txt");
  21.  
  22.     public static void main(String[] args) throws Exception {
  23.  
  24.         // if the arguments are invalid, then print the description of how to specify the program arguments
  25.         if (! validArguments(args)) {
  26.             printHelp();
  27.         } else {
  28.             // add command string to log file
  29.             logFile.addLine("\n" + "Command:" + "\n\n" + args[0] + " " + args[1] + " " + args[2] + " " + args[3]);
  30.  
  31.             // get arguments
  32.             String command = args[0];
  33.             String uriString = args[1];
  34.             String portString = args[2];
  35.             String version = args[3];
  36.  
  37.             // get URI object from uriString
  38.             URI uri = getURI(uriString);
  39.  
  40.             // get port int
  41.             int port = Integer.parseInt(portString);
  42.  
  43.             executeCommand(command, uri, port, version);
  44.  
  45.             // add separator to log file
  46.             logFile.addLine("--------------------------------------------------------------------------------------");
  47.         }
  48.     }
  49.  
  50.     /**
  51.     * Print the description of how to specify the program arguments.
  52.     */
  53.     public static void printHelp() {
  54.         // TODO
  55.         System.out.println("The argument that you entered were wrong:");
  56.         System.out.println("HEAD url(starting with or without http) port(usuallly 80) httpversion(1.0 or 1.1)");
  57.         System.out.println("GET url port httpversion");
  58.         System.out.println("PUT url port httpversion");
  59.         System.out.println("POST url port httpversion");
  60.     }
  61.  
  62.     /**
  63.     * Get URI object from given URI string
  64.     * @param uriString String value of the given URI
  65.     */
  66.     private static URI getURI(String uriString) throws Exception {
  67.         if (! uriString.startsWith("http://") && ! uriString.startsWith("https://")) {
  68.             uriString = "http://" + uriString;
  69.         }
  70.         return new URI(uriString);
  71.     }
  72.  
  73.     /**
  74.     * Execute the command.
  75.     * @param command command string
  76.     * @param uri URI object
  77.     * @param port port number
  78.     * @param version http version (1.0 or 1.1)
  79.     */
  80.     private static void executeCommand(String command, URI uri, int port, String version) throws Exception {
  81.  
  82.         String path = uri.getPath(); // path to file
  83.         String host = uri.getHost();
  84.  
  85.         // Connect to the host.
  86.         Socket clientSocket = null;
  87.         try {
  88.             clientSocket = new Socket(host, port);
  89.         } catch (IOException e) {
  90.             System.out.println("Unable to connect to " + host + ":" + port);
  91.         }
  92.  
  93.         // Create outputstream (convenient data writer) to this host.
  94.         DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  95.  
  96.         // Create an inputstream (convenient data reader) to this host
  97.         BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  98.  
  99.         ArrayList<String> uris;
  100.  
  101.         // Parse command.
  102.         try {
  103.             switch (command) {
  104.                 case "HEAD":
  105.                     head(inFromServer, outToServer, path, host, version);
  106.                     break;
  107.                 case "GET":
  108.                     // als get the returned array of embedded object URI's to request
  109.                     uris = get(inFromServer, outToServer, path, host, version);
  110.                     break;
  111.                 /*case "PUT":
  112.                     put(inFromServer, outToServer, path, host, version);
  113.                     break;*/
  114.                 case "POST":
  115.                     post(inFromServer, outToServer, path, host, version);
  116.                     break;
  117.             }
  118.         }
  119.         catch (Exception e) {
  120.             e.printStackTrace();
  121.         }
  122.  
  123.         // Close the socket.
  124.         clientSocket.close();
  125.  
  126.         // If command is GET and http version is 1.0, then get the embedded objects AFTER the socket was closed
  127.         // (if http version 1.1 was used, the embedded objects are requested inside the get() method)
  128.         if (command.equals("GET") && version.equals("1.0")) {
  129.             // get uris (get2)
  130.             // TODO
  131.         }
  132.     }
  133.  
  134.     private static void head(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
  135.         // Send HTTP command to server.
  136.         if(version.equals("1.0")) {
  137.             outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n\r\n");
  138.         } else {
  139.             outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n" +
  140.                                     "HOST: " + host + "\r\n\r\n");
  141.         }
  142.         logFile.addLine("\n" + "Response:" + "\n");
  143.  
  144.         // Read text from the server
  145.         String response = "";
  146.         while ((response = inFromServer.readLine()) != null) {
  147.             // print response to screen
  148.             System.out.println(response);
  149.             // write response to log file
  150.             logFile.addLine(response);
  151.         }
  152.     }
  153.  
  154.     private static ArrayList<String> get(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
  155.         // Send HTTP command to server.
  156.         if(version.equals("1.0")) {
  157.             outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n\r\n");
  158.         } else {
  159.             outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n" +
  160.                     "HOST: " + host + "\r\n\r\n");
  161.         }
  162.         logFile.addLine("\n" + "Response:" + "\n");
  163.  
  164.         // Read text from the server
  165.         String response = "";
  166.         String outputString = "";
  167.         while ((response = inFromServer.readLine()) != null) {
  168.             // print response to screen
  169.             System.out.println(response);
  170.             // write response to log file
  171.             logFile.addLine(response);
  172.             // add line to output in outputString
  173.             outputString += response;
  174.         }
  175.  
  176.         // Find URI's of embedded objects
  177.         ArrayList<String> uris = new ArrayList<>();
  178.  
  179.         String pattern = "src=\"(.*?)\"";
  180.         Pattern r = Pattern.compile(pattern);
  181.  
  182.         Matcher m = r.matcher(outputString);
  183.         while (m.find( )) {
  184.  
  185.             // if http 1.0 was used, just add the src uri to uris
  186.             if (version.equals("1.0")) {
  187.                 uris.add(m.group(1));
  188.             }
  189.  
  190.             // if http 1.1 was used, then get the file save it
  191.             else {
  192.                 // TODO
  193.             }
  194.  
  195.  
  196.         }
  197.         return uris;
  198.     }
  199.  
  200.     public void get2(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
  201.         // Send HTTP command to server.
  202.         if(version.equals("1.0")) {
  203.             outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n\r\n");
  204.         } else {
  205.             outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n" +
  206.                     "HOST: " + host + "\r\n\r\n");
  207.         }
  208.  
  209.         // Read text from the server
  210.         String response = "";
  211.         String outputString = "";
  212.         while ((response = inFromServer.readLine()) != null) {
  213.             // add line to output in outputString
  214.             outputString += response;
  215.         }
  216.  
  217.         File out = new File("out/" + host + path); // TODO
  218.     }
  219.  
  220.     /**
  221.      * Check if the arguments are valid.
  222.      */
  223.     public static boolean validArguments(String[] arguments) {
  224.         if (arguments.length != 4)
  225.             return false;
  226.         if (! arguments[0].equals("HEAD") && ! arguments[0].equals("GET") && ! arguments[0].equals("PUT") && ! arguments[0].equals("POST"))
  227.             return false;
  228.         if (! isInteger(arguments[2]))
  229.             return false;
  230.         if (! arguments[3].equals("1.0") && ! arguments[3].equals("1.1"))
  231.             return false;
  232.         return true;
  233.     }
  234.  
  235.     /**
  236.      * Check if a string is an integer.
  237.      */
  238.     private static boolean isInteger(String s) {
  239.         try {
  240.             Integer.parseInt(s);
  241.         } catch(NumberFormatException e) {
  242.             return false;
  243.         }
  244.         return true;
  245.     }
  246.  
  247.     ///////////////////////////////////////////////////POST////////////////////////////////////////////////////////////
  248.  
  249.  
  250.  
  251.  
  252.     private static void post(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
  253.  
  254.  
  255.  
  256.                 // Send HTTP command to server.
  257.                 if (version.equals("1.0")) {
  258.                     outToServer.writeBytes("POST " + path + "HTTP/" + version + "\r\n");
  259.                     logFile.addLine("POST " + path + " HTTP/" + version + "\r\n");
  260.                     outToServer.writeBytes("Host: " + host + "\r\n");
  261.                     logFile.addLine("Host: " + host + "\r\n");
  262.                     outToServer.writeBytes("Content-Type: multipart/form-data" + "\r\n");
  263.                     logFile.addLine("Content-Type: multipart/form-data" + "\r\n");
  264.                     outToServer.writeBytes("Content-Length: 11" +  "\r\n");
  265.                     logFile.addLine("Content-Length: 9" + "\r\n");
  266.                     outToServer.writeBytes("\r\n");
  267.                     logFile.addLine("\r\n");
  268.                     outToServer.writeBytes("name=test");
  269.                     logFile.addLine("name=test");
  270.                 } else { // not yet implemented
  271.                     outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n" +
  272.                             "HOST: " + host + "\r\n\r\n");
  273.                 }
  274.                 logFile.addLine("\n" + "Response:" + "\n");
  275.  
  276.                 // Read text from the server
  277.                 String response;
  278.                 while ((response = inFromServer.readLine()) != null) {
  279.                     // print response to screen
  280.                     System.out.println(response);
  281.                     // write response to log file
  282.                     logFile.addLine(response);
  283.                 }
  284.             }
  285.  
  286.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement