【发布时间】:2012-06-14 00:36:35
【问题描述】:
一位朋友向我展示了在 C# 中实现 HTTP POST 的示例代码,并在 WINFORM 应用程序中运行: http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/
并在 METRO APP 中实现:
// this is what we are sending
string post_data = "user=user@example.com&pass=example123";
// this is where we will send it
string uri = "http://app.proceso.com.mx/win8/login";
// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = await request.GetRequestStreamAsync();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
// grab te response and print it out to the console along with the status code
WebResponse response = await request.GetResponseAsync();
//var a = new StreamReader(response.GetResponseStream()).ReadToEnd();
StreamReader requestReader = new StreamReader(response.GetResponseStream());
String webResponse = requestReader.ReadToEnd();
我意识到,HttpWebRequest 不包含 ProtocolVersion 并在此行中向我抛出此错误:
WebResponse response = await request.GetResponseAsync();
// ERROR: The remote server returned an error: (417) Expectation Failed.
我猜最后一个属性是解决方案。我怎么解决这个问题? 提前致谢
【问题讨论】:
-
尝试将以下内容放在顶部:
ServicePointManager.Expect100Continue = false;另外,您为什么使用异步版本的方法,然后使用await阻塞,所有这些功能都有同步版本。跨度>
标签: c# httpwebrequest http-headers microsoft-metro