【发布时间】:2015-04-14 20:34:48
【问题描述】:
我正在尝试从 Windows Phone 应用程序向网站发出 WebRequest。 但对我来说,从服务器获得响应也很重要。 这是我的代码:
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Ahri</string>";
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await stream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
不幸的是,我不知道如何从服务器获得响应。 有人有想法吗?
提前致谢。
感谢@max,我找到了解决方案并想在上面分享。 这是我的代码的样子:
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Claor</string>";
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
string responseFromServer = "no response";
HttpWebRequest httpWebRequest = HttpWebRequest.Create(requestUri) as HttpWebRequest;
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (Stream requestStream = await httpWebRequest.GetRequestStreamAsync())
{
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await requestStream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
WebResponse webResponse = await httpWebRequest.GetResponseAsync();
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
}
希望以后能对大家有所帮助。
【问题讨论】:
-
我们不知道您的服务是做什么的,它的外观如何。您希望我们如何回答?
-
我建议你应该使用
HttpClient而不是HttpWebRequest。为此,您可能需要添加 Microsoft 的额外 Nu-Get 包。这将使您的网络通话变得容易。如需进一步帮助,请简要介绍您的问题..
标签: c# windows-phone-8 http-post