使用C#发送HTTP POST请求

7

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

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

1个回答

9

这是因为你需要使用等号=来给你发布的参数赋值:

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脚本具有与问题中使用的不同的参数名称。


我已经尝试过了,但仍然存在相同的问题。 - abdallah
我更新了我的回答。我还添加了一个fiddle,这样你就可以自己测试,它确实有效。 - Fabien ESCOFFIER
这是因为您的PHP脚本接受的参数与您在问题中公开的参数名称不同。 - Fabien ESCOFFIER
你的 PHP 脚本使用哪些参数名称? - Fabien ESCOFFIER
我怎么能做到不添加 "=&Login=Login" 呢? - abdallah
似乎您的问题源于您的PHP脚本,正如您可以看到的fiddle工作。 - Fabien ESCOFFIER

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接