daily pastebin goal
8%
SHARE
TWEET

Untitled

a guest Apr 16th, 2018 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package lab_redes;
  2.  
  3. import java.net.Socket;
  4.  import java.io.*;
  5.  import java.net.*;
  6.  import java.util.*;
  7.  import java.net.InetAddress.*;
  8.  
  9.     class HttpRequest implements Runnable {
  10.  
  11.  // Constants
  12.  // Recognized HTTP methods
  13.         final static class HTTP_METHOD
  14.  {
  15.         final static String GET = "GET";
  16.         final static String HEAD = "HEAD";
  17.         final static String POST = "POST";
  18.  }
  19.  
  20.         final static String HTTPVERSION = "HTTP/1.0";
  21.         final static String CRLF = "\r\n";
  22.         Socket socket;
  23.      
  24.     // Constructor
  25.     public HttpRequest(Socket socket) throws Exception
  26.        {
  27.             this.socket = socket;
  28.        }
  29.        
  30.                 public HttpRequest() {
  31.         }
  32.     // Implement the run() method of the Runnable interface.
  33.     @Override
  34.     public void run() {
  35.         try {
  36.         processRequest();
  37.     } catch (Exception e) {
  38.         System.out.println(e);
  39.     }
  40.  
  41.     }
  42.     private void processRequest() throws Exception
  43.     {
  44.            
  45. DataOutputStream os = new DataOutputStream(socket.getOutputStream());
  46. /* InputStream = An InputStreamReader is a bridge from byte streams to character streams: It reads
  47. bytes and decodes them into characters using a specified charset. The charset
  48. that it uses may be specified by name or may be given explicitly, or
  49. the platform's default charset may be accepted.*/
  50.            
  51. /*
  52. BufferedReader = Reads text from a character-input stream, buffering characters so as
  53. to provide for the efficient reading of characters, arrays, and lines.          
  54.                                 */            
  55. /*
  56. A data output stream lets an application write primitive Java data types to an
  57. output stream in a portable way. An application can then use a data
  58. input stream to read the data back in.
  59.             */          
  60.    
  61.  // Get the input and output streams of the socket.
  62.             InputStream ins = socket.getInputStream();
  63.             DataOutputStream outs = new DataOutputStream(socket.getOutputStream());
  64.  
  65.  // Set up input stream filters
  66.             BufferedReader br = new BufferedReader(new InputStreamReader(ins));
  67.            
  68. // Get the request line of the HTTP request
  69.             String requestLine = br.readLine();
  70.  
  71.  // Display the request line
  72.             System.out.println();
  73.             System.out.println("Request:");
  74.             System.out.println(" " + requestLine);
  75. // Get and display the header lines.
  76.             String headerLine = null;
  77.             while ((headerLine = br.readLine()).length() != 0) {
  78.             System.out.println(headerLine);
  79.                                                                }
  80.            
  81. // Extract the filename from the request line.
  82. StringTokenizer tokens = new StringTokenizer(requestLine);
  83. tokens.nextToken();  // skip over the method, which should be "GET"
  84. String fileName = tokens.nextToken();
  85.  
  86. // Prepend a "." so that file request is within the current directory.
  87. fileName = "." + fileName;
  88.  
  89.  
  90. //we will use a try/catch construction to set the boolean variable fileExists to false. Later in the code, we
  91. //will use this flag to construct an error response message, rather than try to send a nonexistent file.
  92. // Open the requested file.
  93. FileInputStream fis = null;
  94. boolean fileExists = true;
  95. try {
  96.     fis = new FileInputStream(fileName);
  97. } catch (FileNotFoundException e) {
  98.     fileExists = false;
  99. }
  100.  
  101. // Construct the response message.
  102. // Debug info for private use
  103.     System.out.println("Partiu");
  104.     System.out.println(requestLine);
  105.     while ((headerLine = br.readLine()).length() != 0) {
  106.         System.out.println(headerLine);
  107.     }
  108.    
  109.     // Construct the response message.
  110.         String statusLine = null;
  111.         String contentTypeLine = null;
  112.         String entityBody = null;
  113.         if (fileExists) {
  114.         statusLine = "HTTP/1.0 200 OK" + CRLF;
  115.         contentTypeLine = "Content-Type: " +
  116.         contentType(fileName) + CRLF;
  117.         } else {
  118.         statusLine = "HTTP/1.0 404 Not Found" + CRLF;
  119.         contentTypeLine = "Content-Type: text/html" + CRLF;
  120.         entityBody = "<HTML>" +
  121.         "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
  122.         "<BODY>Not Found</BODY></HTML>";
  123.         }
  124.     // Send the status line.
  125.         os.writeBytes(statusLine);
  126.  
  127.         // Send the content type line.
  128.         os.writeBytes(contentTypeLine);
  129.  
  130.         // Send a blank line to indicate the end of the header lines.
  131.         os.writeBytes(CRLF);
  132.  
  133.         // Send the entity body.
  134.         if (fileExists) {
  135.         sendBytes(fis, os);
  136.         fis.close();
  137.         } else {
  138.         os.writeBytes(entityBody) ;
  139.         }
  140.  
  141.         // Close streams and socket.
  142.         os.close();
  143.         br.close();
  144.         socket.close();
  145.        
  146.     }
  147.  
  148.     private static void sendBytes(FileInputStream fis,
  149.                   OutputStream os) throws Exception {
  150.     // Construct a 1K buffer to hold bytes on their way to the socket.
  151.     byte[] buffer = new byte[1024];
  152.     int bytes = 0;
  153.    
  154.     // Copy requested file into the socket's output stream.
  155.     while ((bytes = fis.read(buffer)) != -1) {
  156.         os.write(buffer, 0, bytes);
  157.     }
  158.     }
  159.  
  160.     private static String contentType(String fileName) {
  161.     if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
  162.         return "text/html";
  163.     }
  164.     if(fileName.endsWith(".ram") || fileName.endsWith(".ra")) {
  165.         return "audio/x-pn-realaudio";
  166.     }
  167.     return "application/octet-stream" ;
  168.     }
  169.    
  170. }
RAW Paste Data
Top