gpt4 book ai didi

c# - 使用 C# 发送 HTTP POST 请求

转载 作者:太空狗 更新时间:2023-10-29 21:26:48 26 4
gpt4 key购买 nike

我尝试使用带有 POST 的 WebRequest 发送数据,但我的问题是没有数据流式传输到服务器。

string user = textBox1.Text;
string password = textBox2.Text;

ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username" + user + "&password" + password;
byte[] data = encoding.GetBytes(postData);

WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();

WebResponse response = request.GetResponse();
stream = response.GetResponseStream();

StreamReader sr99 = new StreamReader(stream);
MessageBox.Show(sr99.ReadToEnd());

sr99.Close();
stream.Close();

here the result

最佳答案

这是因为您需要使用 = 等号来分配您发布的参数:

byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");

WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

string responseContent = null;

using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}

MessageBox.Show(responseContent);

请参阅发布数据格式中的username=&password=

你可以在这个 fiddle 上测试它.

编辑:

您的 PHP 脚本中的参数名称似乎与您问题中使用的参数名称不同。

关于c# - 使用 C# 发送 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36727537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com