如何从WP7中的服务器获得响应?

时间:2011-06-28 13:01:34

标签: windows-phone-7 httpwebrequest getresponse

我正在尝试使用WP7上的HttpWebRequest类发送请求,但我没有得到任何响应...... 这是我的代码:

            InitializeComponent();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            tbResponse.Text = reader.ReadToEnd();

            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
            Console.ReadLine();

此外,我使用此扩展名:click here,但我在Windows控制台应用程序上测试它并没有任何问题,所以我认为问题是我对WP7一无所知。< / p>

1 个答案:

答案 0 :(得分:6)

你需要像这样发出异步请求:

var webRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
webRequest.BeginGetResponse(new AsyncCallback(request_CallBack), webRequest );

和响应处理程序:

void request_CallBack(IAsyncResult result)
{
        var webRequest = result.AsyncState as HttpWebRequest;
        var response = (HttpWebResponse)WebRequest.EndGetResponse(result);
        var baseStream = response.GetResponseStream();

            // if you want to read binary response
            using (var reader = new BinaryReader(baseStream))
            {
                DataBytes = reader.ReadBytes((int)baseStream.Length);
            }

            // if you want to read string response
            using (var reader = new StreamReader(baseStream))
            {
                Result = reader.ReadToEnd();
            }
}

这是我开发的一个帮助程序类,用于在开发Windows Phone 7应用程序时处理我的Web请求:

http://www.manorey.net/mohblog/?p=17&preview=true