使用WebClient / HttpWebRequest – WP7从https检索XML

我正在尝试从服务器检索XML文档并将其作为字符串存储在本地。 在桌面.Net我不需要,我只是做了:

string xmlFilePath = "https://myip/"; XDocument xDoc = XDocument.Load(xmlFilePath); 

但是在WP7上会返回:

 Cannot open 'serveraddress'. The Uri parameter must be a relative path pointing to content inside the Silverlight application's XAP package. If you need to load content from an arbitrary Uri, please see the documentation on Loading XML content using WebClient/HttpWebRequest. 

所以我从这里开始使用WebClient / HttpWebRequest示例,但现在它返回:

 The remote server returned an error: NotFound. 

是因为XML是https路径吗? 或者因为我的路径不是以.XML结尾? 我怎么知道的? 谢谢你的帮助。

这是代码:

  public partial class MainPage : PhoneApplicationPage { WebClient client = new WebClient(); string baseUri = "https://myip:myport/service"; public MainPage() { InitializeComponent(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler( client_DownloadStringCompleted); } private void Button1_Click(object sender, RoutedEventArgs e) { client.DownloadStringAsync (new Uri(baseUri)); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) resultBlock.Text = "Using WebClient: " + e.Result; else resultBlock.Text = e.Error.Message; } private void Button2_Click(object sender, RoutedEventArgs e) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(baseUri)); request.BeginGetResponse(new AsyncCallback(ReadCallback), request); } private void ReadCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream())) { string resultString = streamReader1.ReadToEnd(); resultBlock.Text = "Using HttpWebRequest: " + resultString; } } } 

我宁愿认为你的事情过于复杂。 下面是一个非常简单的示例,它通过HTTPS从URI请求XML文档。

它以字符串forms异步下载XML,然后使用XDocument.Parse()加载它。

  private void button2_Click(object sender, RoutedEventArgs e) { WebClient wc = new WebClient(); wc.DownloadStringCompleted += HttpsCompleted; wc.DownloadStringAsync(new Uri("https://domain/path/file.xml")); } private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None); this.textBox1.Text = xdoc.FirstNode.ToString(); } }