在 C# for Windows Phone 中使用 GetResponse 时遇到问题

本文关键字:GetResponse 遇到 问题 for Windows Phone | 更新日期: 2023-09-27 18:35:55

当我使用

 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

我收到一条错误消息,指出

'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no   extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference? 

我添加了以下参考,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp23.Resources;
using System.IO;
using System.Text;
using System.Threading;

我错过了什么吗??或者我应该怎么做,才能使这项工作正常工作!

在 C# for Windows Phone 中使用 GetResponse 时遇到问题

在Windows Phone中,您需要执行可能需要50毫秒异步时间的所有操作。由于 Web 请求可能需要更长的时间,因此 Microsoft 从类中删除了同步方法。相反,您需要使用异步方法:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new System.Uri("http://www.google.com"));
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request); 
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
    HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
    using(HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult))
    {
        using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
        {
            string results = httpwebStreamReader.ReadToEnd();
            //execute UI stuff on UI thread.
            Dispatcher.BeginInvoke(() => TextBlockResults.Text = results);
        }
    }
}