由于' WebRequest'导致GetResponse()错误

时间:2017-01-06 14:38:41

标签: c# webrequest getresponse

我正在尝试向Googles API发出请求。但我在GetResponse()收到错误。我得到的错误是......

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

Visual Studio为我提供了用BeginGetResponse()替换它的选项,但我不确定如何格式化代码或更改我已经完成的任务。任何人都可以指出我有权解决这个问题吗?我可能错过了一些集会......但我不认为我是。

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 个答案:

答案 0 :(得分:2)

你可以使用这样的异步版本:

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

然后使用FinishWebRequest方法,一旦远程服务器发送响应,将调用该方法:

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

或者如果您更喜欢使用匿名方法:

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