我正在使用框架4.5创建一个在Visual Studio 2013中使用restful POST方法的方法。这是windows_phone_8(针对Phone OS 8.0)应用程序。这是我的代码。
static string HttpPost(string url, string[] paramName, string[] paramVal)
{
HttpWebRequest req = WebRequest.Create(new Uri(url))
as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// Build a string with all the params, properly encoded.
// We assume that the arrays paramName and paramVal are
// of equal length:
StringBuilder paramz = new StringBuilder();
for (int i = 0; i < paramName.Length; i++)
{
paramz.Append(paramName[i]);
paramz.Append("=");
paramz.Append(HttpUtility.UrlEncode(paramVal[i]));
paramz.Append("&");
}
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz.ToString());
req.ContentLength = formData.Length;
// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
// Pick up the response:
string result = null;
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
此方法在Windows Phone 8应用程序中有两个构建错误,但在Windows应用程序中工作正常。
错误1&#39; System.Net.HttpWebRequest&#39;不包含的定义 &#39; GetRequestStream&#39;没有扩展方法&#39; GetRequestStream&#39; 接受类型为#System; Net.Net.HttpWebRequest&#39;的第一个参数。可以 找到(你错过了使用指令或汇编引用吗?)
Error 2 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a
类型&#39; System.Net.HttpWebRequest&#39;的第一个参数可以找到(是 你错过了使用指令或程序集引用?)
答案:
我可以通过更改代码来解决它......
static async Task<string> HttpPost(string url, string[] paramName, string[] paramVal)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Build a string with all the params, properly encoded.
// We assume that the arrays paramName and paramVal are
// of equal length:
StringBuilder paramz = new StringBuilder();
for (int i = 0; i < paramName.Length; i++)
{
paramz.Append(paramName[i]);
paramz.Append("=");
paramz.Append(HttpUtility.UrlEncode(paramVal[i]));
paramz.Append("&");
}
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz.ToString());
request.ContentLength = formData.Length;
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
stream.Write(formData, 0, formData.Length);
}
// Pick up the response:
string result = null;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
呼叫部分就像
private async void btn_Login_Click(object sender, RoutedEventArgs e)
{
var response = await HttpPost(url, paramName, paramVal);
}
由于 塞巴斯蒂安