GetResponse() error due to 'WebRequest'

2k Views Asked by At

I am trying to make a request to Googles API. But I am getting an error with GetResponse(). The error I am getting is...

'WebRequest' does not contain a definition for 'GetResponse'...

Visual Studio gives me the option to replace that with BeginGetResponse(), but I am not sure how to format the code or change what I already have to accomplish this. Can anyone point me in the right to direction to resolve this? It is possible I am missing some assemblies... but I don't think I am.

private void SearchButton_Click(object sender, RoutedEventArgs e)
    {    
      var address = addressInput.Text;
      var requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false", Uri.EscapeDataString(address));

      MessageBox.Show(requestUri.ToString());


      var request = WebRequest.Create(requestUri);
      var response = request.GetResponse();
      var xdoc = XDocument.Load(response.GetResponseStream());    

      var result = xdoc.Element("GeocodeResponse").Element("result");
      var locationElement = result.Element("geometry").Element("location");
      var lat = locationElement.Element("lat");
      var lng = locationElement.Element("lng");
}
1

There are 1 best solutions below

7
On BEST ANSWER

You could use the asynchronous version like this:

var request = WebRequest.Create(requestUri);
request.BeginGetResponse(this.FinishWebRequest, request);

and then have the FinishWebRequest method which will be invoked once the remote server sends the response:

private void FinishWebRequest(IAsyncResult result)
{
    var request = (HttpWebRequest)result.AsyncState;
    using (var response = request.EndGetResponse(result))
    using (var responseStream = response.GetResponseStream())
    {
        var xdoc = XDocument.Load(responseStream);
        ...
    }
}

or if you prefer using an anonymous method:

var request = WebRequest.Create(requestUri);
request.BeginGetResponse(result => 
{
    using (var response = request.EndGetResponse(result))
    using (var responseStream = response.GetResponseStream())
    {
        var xdoc = XDocument.Load(responseStream);
        ...
    }
}, null);