【发布时间】:2023-04-07 02:10:01
【问题描述】:
我已经在这里阅读了很长时间,但在这种情况下,我没有进一步了解。 我是 Windows Phone 开发的新手,面临以下问题。
如果我必须发布 xml 请求消息,我正在调用 web 服务。我的代码在常规 c# 中工作(见下面的代码)
private static string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
但对于 Windows Phone (8) 开发,它需要异步。在网上搜索并尝试了这里给出的各种示例后,我得到了以下代码:
private async void DoCallWS()
{
string url = "<my_url>";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string requestXml = "<my_request_xml>";
// convert request to byte array
byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);
// Write the bytes to the stream
await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
//return reader.ReadToEnd();
string result = reader.ReadToEnd();
}
}
}
字符串结果具有我尝试发送的请求 xml 消息的值....
我知道 async void 方法不是首选,但我稍后会解决这个问题。
我也尝试遵循 Matthias Shapiro (http://matthiasshapiro.com/2012/12/10/window-8-win-phone-code-sharing-httpwebrequest-getresponseasync/) 描述的解决方案,但这导致代码崩溃
请指点我正确的方向:)
谢谢弗兰克
【问题讨论】:
-
您的问题到底是什么?您使用的代码有什么问题。
-
我没有从网络服务中得到答案。 reader.ReadToEnd() 具有我的请求参数
的值
标签: c# .net windows-phone-8 httpwebrequest async-await