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

标签 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

最佳答案

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

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/

相关文章:

java - 服务抛出未知主机异常 Android 应用程序

c# - SQL Assembly WebResponse和字符串解析非常慢

c# - 使用 WatiN 爬行至 google 上的下一页

Django rest framework - 在 POST 后将新创建的对象的 id 传回响应

c# - 在 Rx 中实现滑动窗口的问题

ios - 如何在使用 RestKit 时发帖

php - 在表格中的每一行添加一个 php 按钮

Android 记录并修改所有 HTTP 请求

c# - 如何在 richtextbox 滚动条背景上突出显示选定文本的相对位置

c# - 注释验证不起作用