2011-10-17 82 views
3

我想發送HTTP請求,並通過C#套接字接收來自服務器的響應,並且我是新的這種語言。HTTP over C#套接字

我已經寫了下面的代碼(IP正確解析):

IPEndPoint RHost = new IPEndPoint(IP, Port); 
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
socket.Connect(RHost); 

String HTTPRequestHeaders_String = "GET ?q=fdgdfg HTTP/1.0 
Host: google.com 
Keep-Alive: 300 
Connection: Keep-Alive 
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16 
Referer: http://google.com/"; 

MessageBox.Show(HTTPRequestHeaders_String, "Request"); 

byte[] HTTPRequestHeaders = System.Text.Encoding.ASCII.GetBytes(HTTPRequestHeaders_String); 
socket.Send(HTTPRequestHeaders, SocketFlags.None); 

String Response = ""; 
byte[] buffer = new byte[(int) socket.ReceiveBufferSize]; 

int bytes; 
do 
{ 
    // On this lane program stops to react 
    bytes = socket.Receive(buffer); 
    // This line cannot be reached, tested with breakpoint 
    Response += Encoding.ASCII.GetString(buffer, 0, bytes); 
} 
while (bytes >= 0); 

MessageBox.Show(Response, "Response"); 

我到底做錯了什麼?我只需要加載完整的HTML頁面,或至少從響應字符(我甚至不能做到這一點)。

+3

使用'HttpWebRequest'類。 – SLaks

+2

@SLaks我會更進一步 - 'WebClient' ... –

+1

我需要創建HTTP請求標頭爲一個字符串,是否有可能在這些類中? –

回答

5

我會建議尋找到協議本身,如果你想這樣做原材料,http://www.w3.org/Protocols/HTTP/1.0/spec.html#Request

並嘗試發送CRLF終止請求;)

+0

哇,我在這個問題上想了5個小時,忘記了終止請求,非常感謝! :) –

+0

現在,你的問題解決了,你已經學會了如何從頭開始創建一個Http頭,現在是切換到更高抽象層次的時候了。如前所述,使用'HttpWebRequest'或'WebClient' –

1
var webClient = new WebClient(); 
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
Stream responseStream = webClient.OpenRead("http://www.google.com"); 
if (responseStream != null) 
{ 
    var responseReader = new StreamReader(responseStream); 
    string response = responseReader.ReadToEnd(); 
    MessageBox.Show(response); 
}