HTTP 協議實現

來源:互聯網
上載者:User

標籤:connect   keep   end   throw   nec   服務   response   字元   函數   

一、超文字傳輸通訊協定 (HTTP)及HTTP包
    HTTP協議用於在Internet上發送和接收訊息。HTTP協議是一種請求-應答式的協議——用戶端發送一個請求,伺服器返回該請求的應答,所有的請求與應答都是HTTP包。HTTP協議使用可靠的TCP串連,預設連接埠是80。HTTP的第一個版本是HTTP/0.9,後來發展到了HTTP/1.0,現在最新的版本是HTTP/1.1。HTTP/1.1由RFC 2616 定義。
    在HTTP中,Client/Server之間的會話總是由用戶端通過建立串連和發送HTTP請求包初始化,伺服器不會主動聯絡用戶端或要求與用戶端建立串連。瀏覽器和伺服器都可以隨時中斷串連,例如,在瀏覽網頁時你可以隨時點擊“停止”按鈕中斷當前的檔案下載過程,關閉與Web伺服器的HTTP串連。 
  1 HTTP請求包
  HTTP請求包(GET、POST等要求方法)由三個部分構成,分別是:方法-URI-協議/版本,要求標頭,請求本文。下面是一個HTTP請求包(GET)的例子:
    Socket socket    = new Socket("127.0.0.1", 8080);
    
    OutputStream os  = socket.getOutputStream();
    InputStream  ins = socket.getInputStream();
    StringBuffer sb=new StringBuffer();
    sb.append("POST /index.jsp HTTP/1.1\r\n");//注意\r\n為斷行符號換行
    sb.append("Accept-Language: zh-cn\r\n");
    sb.append("Connection: Keep-Alive\r\n");
    sb.append("Host: 192.168.0.106\r\n");
    sb.append("Content-Length: 37\r\n");
    sb.append("\r\n");
    sb.append("userName=new_andy&password=new_andy\r\n");
    sb.append("\r\n");
    
    //向Web伺服器發送一個HTTP請求包
    os.write(sb.toString().getBytes());  
    os.close();
請求包的第一行是方法-URI-協議/版本:
    GET就是要求方法,根據HTTP標準,HTTP請求可以使用多種要求方法。HTTP 1.1支援七種要求方法:GET、POST、HEAD、OPTIONS、PUT、DELETE和TRACE等,常用的為要求方法是GET和POST。
    /index.jsp表示URI。URI指定了要訪問的網路資源。
    HTTP/1.1是協議和協議的版本。
    最後一行userName=new_andy&password=new_andy為本文,本文與HTTP頭部有一個空行(\r\n)分隔。這裡需要說明的一點,其中Content-Length說明本文的長度,有的本文長度沒有在頭部說明,只是標明Transfer-Encoding: chunked。關於chunked類型的長度計算方法,見RFC 1626。
    請求包的頭部還會包含許多有關用戶端環境和請求本文的有用資訊,這裡不再描述。
  2 HTTP應答包

  和HTTP請求包相似,由三個部分構成,分別是:協議-狀態碼-描述,應答頭,應答本文。下面是一個HTTP應答的例子:

StringBuffer buffer = new StringBuffer();
   buffer.append("HTTP/1.1 200 OK\r\n");
   buffer.append("Date: Tue, 14 Sep 1999 02:19:57 GMT\r\n");
   buffer.append("Server: Apache/1.2.6\r\n");
   buffer.append("Connection: close\r\n");
   buffer.append("Content-Type: text/html\r\n");
   buffer.append("\r\n");
   buffer.append("<html><head><title>解讀HTTP包樣本</title></head><body>test</body></html>\r\n");
   //bout.write(buffer.toString().getBytes());
   
    
    //向Web伺服器發送一個HTTP請求包
    try {
   this.output.write(buffer.toString().getBytes());
   this.output.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  

HTTP應答包的第一行類似於HTTP請求的第一行,表示所用的協議是HTTP 1.1,伺服器處理請求的狀態代碼200。 
  應答頭也和要求標頭一樣包含許多有用的資訊,例如伺服器類型、日期時間、內容類型和長度等。應答的本文就是伺服器返回的HTML頁面。應答頭和本文之間也用CRLF分隔。 
二、Socket類與ServerSocket類 
  在Java中,通訊端點由java.net.Socket類(用戶端)或java.net.ServerSocket類(伺服器端)表示。應用程式通過端點向網路發送或從網路讀取資料。位於兩台不同機器上的應用軟體通過網路連接發送和接收位元組流,從而實現通訊。要把HTTP包發送給另一個應用,首先要知道對方的IP地址以及其通訊端點的連接埠號碼。
   Socket類代表的是用戶端,它是一個串連遠程伺服器應用時臨時建立的端點。
   ServerSocker類代表的是伺服器端,它啟動後等待來自用戶端的串連請求;一旦接收到請求,ServerSocket建立一個Socket執行個體來處理與該用戶端的通訊。對於伺服器應用,我們不知道用戶端應用什麼時候會試圖串連伺服器,伺服器必須一直處於等待串連的狀態。

  下面是ServerSocket提供了四個建構函式,常用的建構函式的的一種形式為:
  public ServerSocket(int port, int backLog, InetAddress bindingAddress);
  參數:port指定伺服器端監聽用戶端的連接埠;
  backlog為串連請求的最大隊列長度,一旦超越這個長度,伺服器端點開始拒絕用戶端的串連請求。
  bindingAddress是一個java.net.InetAddress的執行個體,指定綁定IP地址。
   建立好ServerSocket執行個體之後,調用它的accept方法,要求它等待傳入的串連請求。只有出現了串連請求時,accept方法才會返回,它的傳回值是一個Socket類的執行個體。隨後,這個Socket對象就可以用來與用戶端應用通訊。
  
  Socket類有許多建構函式,常用的為:
  public Socket(String host, int port)。參數是主機名稱(IP地址或網域名稱)和連接埠號碼。
   參數host是遠程機器的名字或IP地址,port是遠程應用的連接埠號碼。
   成功建立了Socket類的執行個體之後,我們就可以用它來發送和接收位元組流形式的資料,資料一般為HTTP包。
   
   要發送位元組流,首先要調用Socket類的getOutputStream方法獲得一個java.io.OutputStream對象;要從串連的另一端接收位元組流,首先要調用Socket類的getInputStream方法獲得一個java.io.InputStream對象。 
   下面的代碼片斷建立一個與本地HTTP伺服器(127.0.0.1代表本地主機的IP地址)通訊的Socket,發送一個HTTP請求包,準備接收伺服器的應答。

三、讀取HTTP包
  以下我自己設計的一個讀取HTTP包的類SocketRequest。

package com.eri.sas.sms;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketRequest extends Thread
{ // 從指定的Socket的InputStream中讀取資料

 private InputStream input;
 
 private OutputStream output;
 
 private Socket msocket =null;

 private String uri;

 private StringBuffer request = new StringBuffer(); // 用於儲存所有內容

 private int CONTENT_LENGTH = 0; // 實際包內容資料長

 private boolean bePost = false;

 private boolean beHttpResponse = false;

 private boolean beChucked = false;

 private boolean beGet = false;

 private byte crlf13 = (byte) 13; // ‘\r‘

 private byte crlf10 = (byte) 10; // ‘\n‘

 public SocketRequest(InputStream input) {
  this.input = input;
 }

 public SocketRequest(Socket socket) throws IOException {
  this.input = socket.getInputStream();
  this.output = socket.getOutputStream();
  msocket =socket;
 }

 public void run()
 {
  ReadData();
  //
  System.out.println("all content \r\n" + getData());
  
  //
  WirteDate();
  //
  close();
 }
 
 public void WirteDate() {
  /**
   *  HTTP/1.1 200 OK
   Server: Microsoft-IIS/4.0
   Date: Mon, 3 Jan 2005 13:13:33 GMT
   Content-Type: text/html
   Last-Modified: Mon, 11 Jan 2004 13:23:42 GMT
   Content-Length: 90
   
   <html>
   <head>
   <title>解讀HTTP包樣本</title></head><body>
   Hello WORLD!
   </body>
   </html>
   */
    StringBuffer sb=new StringBuffer();
    sb.append("HTTP/1.1 200 OK\r\n");//注意\r\n為斷行符號換行
    sb.append("Server: Microsoft-IIS/4.0\r\n");
    sb.append("Date: Mon, 3 Jan 2005 13:13:33 GMT\r\n");
    sb.append("Content-Type: text/html\r\n");
    sb.append("Last-Modified: Mon, 11 Jan 2004 13:23:42 GMT\r\n");
   // sb.append("Content-Length: 90\r\n");
    sb.append("\r\n");
    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>解讀HTTP包樣本ss</title></head><body>\r\n");
    sb.append("ssssssssssss</body>\r\n");
    
    sb.append("</html>\r\n");
    
    
     StringBuffer buffer = new StringBuffer();
   buffer.append("HTTP/1.1 200 OK\r\n");
   buffer.append("Date: Tue, 14 Sep 1999 02:19:57 GMT\r\n");
   buffer.append("Server: Apache/1.2.6\r\n");
   buffer.append("Connection: close\r\n");
   buffer.append("Content-Type: text/html\r\n");
   buffer.append("\r\n");
   buffer.append("<html><head><title>解讀HTTP包樣本</title></head><body>test</body></html>\r\n");
   //bout.write(buffer.toString().getBytes());
   
    
    //向Web伺服器發送一個HTTP請求包
    try {
   this.output.write(buffer.toString().getBytes());
   this.output.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }

 public void ReadData()
 { // 解析 獲得InputStream的資料

  ReadHeader(); // 頭部

  if (beChucked) // 為Chucked
  {
   int ChuckSize = 0;
   while ((ChuckSize = getChuckSize()) > 0) // 多個Chucked
   {
    readLenData(ChuckSize + 2);// 讀取定長資料
   }
   readLenData(2); // 最後的2位
  }

  if (CONTENT_LENGTH > 0) {
   readLenData(CONTENT_LENGTH);// 讀取定長資料
  }

  uri = "";
  
  parseUri(new String(request));
 }

 private void readLenData(int size) // 讀取定長資料
 {
  int readed = 0; // 已經讀取數
  try {
   int available = 0;// input.available(); //可讀數
   if (available > (size - readed))
    available = size - readed;
   while (readed < size) {
    while (available == 0) { // 等到有資料可讀
     available = input.available(); // 可讀數
    }
    if (available > (size - readed))
     available = size - readed; // size-readed--剩餘數
    if (available > 2048)
     available = 2048; // size-readed--剩餘數
    byte[] buffer = new byte[available];
    int reading = input.read(buffer);
    request = request.append(new String(buffer, 0, reading)); // byte數組相加
    readed += reading; // 已讀字元
   }
  } catch (IOException e) {
   System.out.println("Read readLenData Error!");
  }
 }

 private void ReadHeader() // 讀取頭部 並獲得大小
 {
  byte[] crlf = new byte[1];
  int crlfNum = 0; // 已經串連的斷行符號換行數 crlfNum=4為頭部結束
  try {
   while (input.read(crlf) != -1) // 讀取頭部
   {
    if (crlf[0] == crlf13 || crlf[0] == crlf10) {
     crlfNum++;
    } else {
     crlfNum = 0;
    } // 不是則清
    request = request.append(new String(crlf, 0, 1)); // byte數組相加
    if (crlfNum == 4)
     break;
   }
  } catch (IOException e) {
   System.out.println("Read Http Header Error!");
   return;
  }

  String tempStr = (new String(request)).toUpperCase();

  // 這裡我只處理了GET與POST方法
  String strMethod = tempStr.substring(0, 4);
  if (strMethod.equals("GET ")) // 前
  {
   beGet = true;
  } else if (strMethod.equals("POST")) {
   bePost = true;
   getContentlen_Chucked(tempStr);
  } else {
   System.out.println("不支援的HTTP包類型");

  } // 其它的其它類型 暫不支援
 }

 private void getContentlen_Chucked(String tempStr) // 獲得長度 CONTENT-LENGTH 或
              // 是否為CHUNKED型
 {
  String ss1 = "CONTENT-LENGTH:";
  String ss2 = new String("TRANSFER-ENCODING: CHUNKED");

  int clIndex = tempStr.indexOf(ss1);
  int chuckIndex = tempStr.indexOf(ss2); // 為CHUNKED型
  byte requst[] = tempStr.getBytes();
  if (clIndex != -1) { // 從clIndex+1起至\r\n
   StringBuffer sb = new StringBuffer();

   for (int i = (clIndex + 16);; i++) {
    if (requst[i] != (byte) 13 && requst[i] != (byte) 10) {
     sb.append((char) requst[i]);
    } else
     break;
   }

   CONTENT_LENGTH = Integer.parseInt(sb.toString()); // 正式的HTML檔案的大小
   // System.out.println("CONTENT_LENGTH== "+CONTENT_LENGTH);
  }
  if (chuckIndex != -1)
   beChucked = true;
 }

 private int getChuckSize() // Chuck大小
 {
  byte[] crlf = new byte[1];
  StringBuffer sb1 = new StringBuffer();

  int crlfNum = 0; // 已經串連的斷行符號換行數 crlfNum=4為頭部結束

  try {
   while (input.read(crlf) != -1) // 讀取頭部
   {
    if (crlf[0] == crlf13 || crlf[0] == crlf10) {
     crlfNum++;
    } else {
     crlfNum = 0;
    } // 不是則清
    sb1.append((char) crlf[0]);
    request = request.append(new String(crlf, 0, 1)); // byte數組相加
    if (crlfNum == 2)
     break;
   }
  } catch (IOException e) {
   System.out.println("Read Http Package Error!");
   return 0;
  }

  return Integer.parseInt((sb1.toString()).trim(), 16); // 16進控制
 }

 // 通過此來進行過濾,是否為發至目標伺服器的HTTP包
 private String parseUri(String requestString)
 {
  int index1, index2;
  index1 = requestString.indexOf(‘ ‘);
  if (index1 != -1) {
   index2 = requestString.indexOf(‘ ‘, index1 + 1);
   if (index2 > index1)
    return requestString.substring(index1 + 1, index2);
  }
  return null;
 }

 public String getData()
 {
  return request.toString();
 }
 

 /**
  * close
  */
 public void close() {
  try {
   if (input != null)
    input.close();
   if (msocket != null)
    msocket.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

HTTP 協議實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.