如何使用ASP.net C#将HTTP Post请求发送到套接字

问题描述 投票:1回答:1

我正在开发我的项目,我是ASP.NET的新手。

我想点击按钮时将HTTP发送请求发送到套接字

这是我的代码。

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();
}

谢谢你的帮助。

c# asp.net sockets tcp http-post
1个回答
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.");     
}

希望这可以帮助..

© www.soinside.com 2019 - 2024. All rights reserved.