WP7中HttpWebRequest的使用方法之GET方式

时间:2022-03-14 03:12:18

  在WP7中的HttpWebRequest与在C#中的使用方式大致是一样的,但是在WP7中微软移去了同步的操作方式,所有的操作方式都改为异步,(提升用户体验,在请求过程中界面保持流畅)。

下面给出两种编码方式 :其实都是一样的,只是第一种使用了独立方法的完成,(便于阅读和理解),第二种是直接用委托写在同一个方法里。

第一种:

 1         private void button2_Click(object sender, RoutedEventArgs e)
 2         {
 3             string url = "http://www.cnblogs.com/xdpxyxy";
 4 
 5             HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
 6 
 7             myRequest.Method = "GET";
 8 
 9             //开始对服务器资源异步请求
10             myRequest.BeginGetResponse(new AsyncCallback(GetRqCallback), myRequest);
11         }
12 
13 
14         private void GetRqCallback(IAsyncResult asynchronousResult)
15         {
16             //获取开始异步请求的object对象
17             HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
18 
19             //结束请求
20             HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
21 
22             //得到服务器返回资源
23             Stream streamResponse = response.GetResponseStream();
24 
25             StreamReader streamRead = new StreamReader(streamResponse);
26 
27             string responseString = streamRead.ReadToEnd();
28 
29             streamResponse.Close();
30 
31             streamRead.Close();
32 
33         }

第二种:

 1  HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(getUrl));
 2             httpWebRequest.Method = "GET";
 3             httpWebRequest.BeginGetResponse((IAsyncResult responseCallback) =>
 4             {
 5                 HttpWebRequest webRequest2 = responseCallback.AsyncState as HttpWebRequest;
 6                 HttpWebResponse webResponse = (HttpWebResponse)webRequest2.EndGetResponse(responseCallback);
 7                 Stream streamResponse = webResponse.GetResponseStream();
 8                 StreamReader sr = new StreamReader(streamResponse);
 9                 string str = sr.ReadToEnd();
10             }, httpWebRequest);