2014-03-27 19 views
3

我試圖手動建立一個HTTP請求(作爲一個字符串),並把它通過TCP套接字,這就是我想要做的事:當通過TCP套接字發送手動製作的HTTP請求時,爲什麼會收到HTTP 400的錯誤請求響應?

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.MalformedURLException; 
import java.net.Socket; 
import java.net.URL; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

/** 
* SimpleHttpClient.java (UTF-8) 
* 
* Mar 27, 2014 
* 
* @author tarrsalah.org 
*/ 
public class SimpleHttpClient { 
    private static final String StackOverflow = "http://stackoverflow.com/"; 

    public static void main(String[] args) { 

//  if (args.length < 1) { 
//   System.out.println("Usage : SimpleHttpClient <url>"); 
//   return; 
//  } 

     try { 
      URL url = new URL(StackOverflow); 
      String host = url.getHost(); 
      String path = url.getPath(); 
      int port = url.getPort(); 
      if (port < 80) { 
       port = 80; 
      } 

      //Construct and send the HTTP request 
      String request = "GET" + path + "HTTP/1.1\n"; 
      request += "host: " + host; 
      request += "\n\n"; 

      // Open a TCP connection 
      Socket socket = new Socket(host, port); 
      // Send the request over the socket 
      PrintWriter writer = new PrintWriter(socket.getOutputStream()); 
      writer.print(request); 
      writer.flush(); 
      // Read the response 
      BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      String next_record = null; 
      while ((next_record = reader.readLine()) != null) { 
       System.out.println(next_record); 
      } 
      socket.close(); 
     } catch (MalformedURLException ex) { 
      Logger.getLogger(SimpleHttpClient.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (IOException ex) { 
      Logger.getLogger(SimpleHttpClient.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

但我得到這個消息的反應不管URL如何選擇:

HTTP/1.0 400 Bad request 
Cache-Control: no-cache 
Connection: close 
Content-Type: text/html 

<html><body><h1>400 Bad request</h1> 
Your browser sent an invalid request. 
</body></html> 

爲什麼?

+0

可能重複的[手動發送HTTP請求通過套接字](http://stackoverflow.com/questions/10673684/send-http-request-manually-via-socket) – Jeroen

+1

如何檢查你發送的內容? HTTP跟蹤?寫入System.out? –

回答

3

由於Julian Reschke的建議,我缺少絲束空格字符(其中一個HTTP動詞之後和路徑之後的第二)的

String request = "GET " + path + " HTTP/1.1\n"; 
//     ^  ^
0

實際上,我有點不確定這是否解決您的問題,但如果你讀RFC2616, section 5你會注意到它很特別提到CRLF「後Request-line和頭S,所以你可能會丟失一些\r」在你的代碼爲S 。

乾杯,

+0

會導致400? –

相關問題