【问题标题】:How to send HTTP Post request to a socket using ASP.net C#如何使用 ASP.net C# 将 HTTP Post 请求发送到套接字
【发布时间】:2012-02-01 04:44:22
【问题描述】:

我正在开发我的项目,而且我是 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();
}

tnx 的帮助。

【问题讨论】:

  • 什么是socket?这应该是Socket(如System.Net.Sockets.Socket?另外,如果您正在使用Http,那么首选方法是使用HttpClient 类。
  • HttpClient,或者WebClientWebRequest。绝对不是套接字。

标签: c# asp.net sockets tcp http-post


【解决方案1】:

您可以使用类似下面的代码通过 POST 方法发送 HTTP 请求...

会自动创建一个套接字(Server + Port)来处理服务器上的数据以处理请求。

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.");     
}

希望这会有所帮助..

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多