使用C#发送HTTP POST请求

时间:2016-04-19 19:20:05

标签: c# post httpwebrequest httprequest

我尝试使用带有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

1 个答案:

答案 0 :(得分:7)

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

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