3

I'm trying to send a request with the HttpWebRequest class on WP7, but I don't get any response... Here is my code:

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

Moreover, I use this extension: click here, but I tested it on a Windows Console Application and there wasn't any problem, so I think the problem is that I don't know something about WP7.

laszlokiss88
  • 3,883
  • 2
  • 17
  • 25
  • 6
    Don't make synchronous requests; they freeze the UI. `GetResponse()` doesn't exist for a reason. – SLaks Jun 28 '11 at 13:04
  • See also [DownloadStringTaskAsync on WP7 hangs when retrieving Result](http://stackoverflow.com/questions/6448819/downloadstringtaskasync-on-wp7-hangs-when-retrieving-result) – Richard Szalay Jun 28 '11 at 23:01

1 Answers1

6

You need to make asynchronous requests like this:

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

and the response handler:

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

Here is a helper class I developed to handle my web request needs during development of windows phone 7 apps:

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

Mo Valipour
  • 12,868
  • 10
  • 56
  • 86