Tai*_*red 3 c# post http 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();
}
Run Code Online (Sandbox Code Playgroud)
此输出为:
webResponse.ContentLength = -1
webResponse.ContentType = text/html
webResponse.ContentEncoding为空
responseString是带有标题和正文的HTML.
但是,如果我将相同的网址发布到浏览器(http://example.com/post.php?Key1=some_value&Key2=some_other_value),我会得到一个小的XML代码段:
<?xml version="1.0" ?>
<RESPONSE RESULT="SUCCESS"/>
没有与应用程序中相同的HTML.为什么回答如此不同?我需要解析返回的结果,我没有在HTML中获得.我是否必须更改应用程序中的帖子方式?我无法控制接受帖子的服务器端代码.
如果您确实应该使用POSTHTTP方法,那么您会遇到一些错误.首先,这一行:
postData.Append("post.php?");
Run Code Online (Sandbox Code Playgroud)
是不正确的.你想张贴到 post.php,你不想发布值"post.php?" 到页面.只需完全删除此行.
这件作品:
... WebRequest.Create("http://example.com/");
Run Code Online (Sandbox Code Playgroud)
需要post.php加入它,所以......
... WebRequest.Create("http://example.com/post.php");
Run Code Online (Sandbox Code Playgroud)
再次假设你实际上应该是POST指向页面而不是GETing.如果你应该使用GET,那么已经提供的其他答案适用.