我有一个使用以下代码执行 HTTP 发布的 C# 控制台应用程序(.NET 2.0 框架):
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。为什么反应如此不同?我需要解析在 HTML 中没有得到的返回结果。我是否必须更改我在应用程序中发布帖子的方式?我无法控制接受帖子的服务器端代码。