2012-02-01 36 views
1

我正在開發我的項目,我是ASP.NET新手。如何發送HTTP POST請求到使用ASP.net的套接字C#

我想送HTTP POST請求到插座時,我打一個按鈕

這裏是我的代碼。

protect void Button1_click(object sender, EventArgs e) 
{ 
    socket clientSocket = new Socket (addressFamily.InterNetwork, SocketType.Stream, Protocol.TCP); 
    clientSocket.Connect(new IPEndPont.Parse("192.168.1.1", 5550)); 

    A = "1"; // i want to send this variable using HTTP post request 

    clientSocket.Send(Encoding.UTF8.Getbytes(A)); 

    clientSocket.Close(); 
} 

tnx幫助。

+2

什麼是'socket'?這應該是'Socket'(如'System.Net.Sockets.Socket')嗎?另外,如果你使用Http,那麼首選的方法是使用'HttpClient'類。 – 2012-02-01 04:50:12

+3

HttpClient或者' WebClient'或'WebRequest'。絕對不是套接字。 – 2012-02-01 04:51:48

回答

2

您可以使用類似下面的代碼來發送使用POST方法的HTTP請求......

套接字(服務器+端口)將被自動創建來處理服務器上的數據處理請求。

WebRequest request = WebRequest.Create(url); 
request.Method = "POST"; 


string postData = "Data to post here" 

byte[] post = Encoding.UTF8.GetBytes(postData); 

//Set the Content Type  
request.ContentType = "application/x-www-form-urlencoded";  
request.ContentLength = post.Length;  
Stream reqdataStream = request.GetRequestStream();  
// Write the data to the request stream.  
reqdataStream.Write(post, 0, post.Length);  
reqdataStream.Close();  
// If required by the server, set the credentials.  
request.Credentials = CredentialCache.DefaultCredentials;  

WebResponse response = null;  
try  
{ 
    // Get the response.   
    response = request.GetResponse();  
} 
catch (Exception ex)  
{   
    Response.Write("Error Occured.");  
} 

希望這有助於..

+0

thx爲您提供幫助.. – nubiee 2012-02-01 05:55:40