2011-06-28 95 views
3

我想送與WP7 HttpWebRequest類的請求,但我沒有得到任何迴應... 這裏是我的代碼:如何從WP7中的服務器獲取響應?

  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。

+6

不要mak e同步請求;他們凍結了用戶界面。 'GetResponse()'不存在的原因。 – SLaks

+0

另請參見[檢索結果時,WP7上的DownloadStringTaskAsync掛起](http://stackoverflow.com/questions/6448819/downloadstringtaskasync-on-wp7-hangs-when-retrieving-result) –

回答

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(); 
      } 
} 

這是我用來處理我的web請求一個輔助類需要的Windows Phone的開發過程中7個應用程序:

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

相關問題