Advertisement
Guest User

HttpClient

a guest
May 9th, 2016
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.86 KB | None | 0 0
  1. package com.HttpClient;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.net.Socket;
  9. import java.text.ParseException;
  10.  
  11. public class HttpClient {
  12.     public static void main(String[] args) {
  13.         try {
  14.             String header = null;
  15.             if (args.length == 0) {
  16.                 header = readHeader(System.in);
  17.             } else {
  18.                 FileInputStream fis = new FileInputStream(args[0]);
  19.                 header = readHeader(fis);
  20.                 fis.close();
  21.             }
  22.             System.out.println("Заголовок: \n" + header); /* Запрос отправляется на сервер */
  23.             String answer = sendRequest(header); /* Ответ выводится на консоль */
  24.             System.out.println("Ответ от сервера: \n");
  25.             System.out.write(answer.getBytes());
  26.         } catch (Exception e) {
  27.             System.err.println(e.getMessage());
  28.             e.getCause().printStackTrace();
  29.         }
  30.     }
  31.  
  32.     /**
  33.      * Читает поток и возвращает его содержимое в виде строки.
  34.      */
  35.     public static String readHeader(InputStream strm) throws IOException {
  36.         byte[] buff = new byte[64 * 1024];
  37.         int length = strm.read(buff);
  38.         String res = new String(buff, 0, length);
  39.         return res;
  40.     }
  41.  
  42.     /**
  43.      * Отправляет запрос в соответствии с Http заголовком. * * @return ответ от сервера.
  44.      */
  45.     public static String sendRequest(String httpHeader) throws Exception { /* Из http заголовка берется арес сервера */
  46.         String host = null;
  47.         int port = 0;
  48.         try {
  49.             host = getHost(httpHeader);
  50.             port = getPort(host);
  51.             host = getHostWithoutPort(host);
  52.         } catch (Exception e) {
  53.             throw new Exception("Не удалось получить адрес сервера.", e);
  54.         } /* Отправляется запрос на сервер */
  55.         Socket socket = null;
  56.         try {
  57.             socket = new Socket(host, port);
  58.             System.out.println("Создан сокет: " + host + " port:" + port);
  59.             socket.getOutputStream().write(httpHeader.getBytes());
  60.             System.out.println("Заголовок отправлен. \n");
  61.         } catch (Exception e) {
  62.             throw new Exception("Ошибка при отправке запроса: " + e.getMessage(), e);
  63.         } /* Ответ от сервера записывается в результирующую строку */
  64.         String res = null;
  65.         try {
  66.             InputStreamReader isr = new InputStreamReader(socket.getInputStream());
  67.             BufferedReader bfr = new BufferedReader(isr);
  68.             StringBuffer sbf = new StringBuffer();
  69.             int ch = bfr.read();
  70.             while (ch != -1) {
  71.                 sbf.append((char) ch);
  72.                 ch = bfr.read();
  73.             }
  74.             res = sbf.toString();
  75.         } catch (Exception e) {
  76.             throw new Exception("Ошибка при чтении ответа от сервера.", e);
  77.         }
  78.         socket.close();
  79.         return res;
  80.     }
  81.  
  82.     /**
  83.      * Возвращает имя хоста (при наличии порта, с портом) из http заголовка.
  84.      */
  85.     private static String getHost(String header) throws ParseException {
  86.         final String host = "Host: ";
  87.         final String normalEnd = "\n";
  88.         final String msEnd = "\r\n";
  89.         int s = header.indexOf(host, 0);
  90.         if (s < 0) {
  91.             return "localhost";
  92.         }
  93.         s += host.length();
  94.         int e = header.indexOf(normalEnd, s);
  95.         e = (e > 0) ? e : header.indexOf(msEnd, s);
  96.         if (e < 0) {
  97.             throw new ParseException("В заголовке запроса не найдено " + "закрывающих символов после пункта Host.", 0);
  98.         }
  99.         String res = header.substring(s, e).trim();
  100.         return res;
  101.     }
  102.  
  103.     /**
  104.      * Возвращает номер порта.
  105.      */
  106.     private static int getPort(String hostWithPort) {
  107.         int port = hostWithPort.indexOf(":", 0);
  108.         port = (port < 0) ? 80 : Integer.parseInt(hostWithPort.substring(port + 1));
  109.         return port;
  110.     }
  111.  
  112.     /**
  113.      * Возвращает имя хоста без порта.
  114.      */
  115.     private static String getHostWithoutPort(String hostWithPort) {
  116.         int portPosition = hostWithPort.indexOf(":", 0);
  117.         if (portPosition < 0) {
  118.             return hostWithPort;
  119.         } else {
  120.             return hostWithPort.substring(0, portPosition);
  121.         }
  122.     }
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement