无法在 Xamarin 中加载简单页面



我正在使用Xamarin.Forms和可移植项目。在便携式项目中,我尝试使用以下方法下载网页:

public static List<Lesson> ReadCurrentLessons()
{
  var request = (HttpWebRequest)WebRequest.Create(new Uri(timetablePage));
  request.ContentType = "text/html";
  request.Method = "GET";
  var z = request.BeginGetResponse((IAsyncResult ar) =>
  {
    var rq = (HttpWebRequest) ar.AsyncState;
    using (var resp = (HttpWebResponse) rq.EndGetResponse(ar))
    {
      var s = resp.GetResponseStream();
    }
  }, null);
  return null;
}

不幸的是,无论我做什么,它都不起作用:要么调试器不允许我进入第一个 lambda,要么,如果它这样做,ar.AsyncState总是显示为等于 null .

我做错了什么?我已经设置了INTERNET权限,并验证了Android模拟器可以访问互联网。

我正在使用这个,来自Microsoft HTTP 客户端库https://www.nuget.org/packages/Microsoft.Net.Http,而且效果很好

  using (var httpClient = new HttpClient(handler))
        {
            Task<string> contentsTask = httpClient.GetStringAsync(uri); 
            // await! control returns to the caller and the task continues to run on another thread
            string contents = await contentsTask;
            vendors = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MyObject>>(contents);
        }

啊,我明白了...我已经相应地编辑了答案。我已经在基本的HTTP GET上对此进行了测试,并且在提供的两个示例中都有效。下面的示例显示了按钮单击事件中的代码,但我相信您明白您的意图。

选项 1

使用委托方法回调,例如

button.Clicked += (object sender, EventArgs e) => {
    var request = (HttpWebRequest)WebRequest.Create(new Uri(@"http://www.google.co.uk"));
    request.ContentType = "text/html";
    request.Method = "GET";
    request.BeginGetResponse(new AsyncCallback(this.FinishWebRequest),request);
};
private void FinishWebRequest(IAsyncResult result)
{
    HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
}

选项 2

内联处理回调:

button2.Clicked += (object sender, EventArgs e) => {
    var request = (HttpWebRequest)WebRequest.Create(new Uri(@"http://www.google.co.uk"));
    request.ContentType = "text/html";
    request.Method = "GET";
    request.BeginGetResponse(new AsyncCallback((IAsyncResult ar)=>{
        HttpWebResponse response = (ar.AsyncState as HttpWebRequest).EndGetResponse(ar) as HttpWebResponse;
    }),request);
};

我没有什么可以测试响应流功能,但上面的代码将为您提供所需的响应。

最新更新