c# - C# 控制台应用程序中的 HTTP Post 不会返回与浏览器请求相同的内容

标签 c# http post console-application

我有一个 C# 控制台应用程序(.NET 2.0 框架),它使用以下代码执行 HTTP 发布:

StringBuilder postData = new StringBuilder(100);
postData.Append("post.php?");
postData.Append("Key1=");
postData.Append(val1);
postData.Append("&Key2=");
postData.Append(val2);

byte[] dataArray = Encoding.UTF8.GetBytes(postData.ToString());

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://example.com/");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";

httpRequest.ContentLength = dataArray.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(dataArray, 0, dataArray.Length);
requestStream.Flush();
requestStream.Close();

HttpWebResponse webResponse = (HttpWebResponse)httpRequest.GetResponse();

if (httpRequest.HaveResponse == true) {
  Stream responseStream = webResponse.GetResponseStream();
  StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
  String responseString = responseReader.ReadToEnd();
}

这个输出是:
webResponse.ContentLength = -1
webResponse.ContentType = text/html
webResponse.ContentEncoding 为空

responseString 是带有标题和正文的 HTML。

但是,如果我将相同的 URL 发布到浏览器 ( http://example.com/post.php?Key1=some_value&Key2=some_other_value ),我会得到一个小的 XML 片段,例如:

<?xml version="1.0" ?>
<RESPONSE RESULT="SUCCESS"/>

没有与应用程序中相同的 HTML。为什么 react 如此不同?我需要解析我没有在 HTML 中得到的返回结果。我是否必须更改我在应用程序中发帖的方式?我无法控制接受帖子的服务器端代码。

最佳答案

如果您确实应该使用 POST HTTP 方法,那么您有一些错误。首先,这一行:

postData.Append("post.php?");

不正确。您想要将 发布到 post.php,您不想发布值“post.php”?到页面。完全删除这一行。

这一段:

... WebRequest.Create("http://example.com/");

需要添加post.php,所以...

... WebRequest.Create("http://example.com/post.php");

再次假设您实际上应该POSTing 到指定页面而不是GETing。如果您应该使用 GET,则已提供的其他答案适用。

关于c# - C# 控制台应用程序中的 HTTP Post 不会返回与浏览器请求相同的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/544411/

相关文章:

C# 有哪些替代方法可以沿调用链传播事件?

c# - 你怎么算在另一个基地?

android - Android 上的 Youtube - 如何检查它使用的协议(protocol)?

api - 尝试添加 X-Amz-Invocation-Type :Event to existing API Gateway POST method

http - 哪一部分从 url 中省略了哈希片段或者为什么爬虫不简单地发送片段?

ruby-on-rails - Rails : NoMethodError (Undefined method _url for _controller. 创建后我似乎无法正确响应 json。为什么?

php - ajax $_POST 数据然后重定向到新页面

c# - 将 foreach 循环更改为 Parallel.ForEach 和奇怪的错误

c# - 将 DateTimePicker 值设置为 null

perl - 如何使用 Perl 脚本发布文件的内容