C# 无法在Xamarin中加载简单页面
我正在使用Xamarin.Forms和一个可移植项目。在portable项目中,我尝试使用以下方法下载网页:C# 无法在Xamarin中加载简单页面,c#,android,xamarin,xamarin.forms,C#,Android,Xamarin,Xamarin.forms,我正在使用Xamarin.Forms和一个可移植项目。在portable项目中,我尝试使用以下方法下载网页: public static List<Lesson> ReadCurrentLessons() { var request = (HttpWebRequest)WebRequest.Create(new Uri(timetablePage)); request.ContentType = "text/html"; request.Method = "GET";
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;
}
公共静态列表ReadCurrentLessons()
{
var request=(HttpWebRequest)WebRequest.Create(新Uri(timetablePage));
request.ContentType=“text/html”;
request.Method=“GET”;
var z=请求。开始响应((IAsyncResult ar)=>
{
var rq=(HttpWebRequest)ar.AsyncState;
使用(var resp=(HttpWebResponse)rq.EndGetResponse(ar))
{
var s=resp.GetResponseStream();
}
},空);
返回null;
}
不幸的是,无论我做什么,它都不起作用:要么调试器不允许我进入第一个lambda,要么,如果调试器允许,ar.AsyncState
总是显示为等于null
我做错了什么?我已经设置了
互联网
权限,并验证了Android emulator可以访问互联网。啊,我明白了……我已经相应地编辑了答案。我已经在一个基本的HTTPGET上对此进行了测试,并且在提供的两个示例中都可以使用。下面的示例显示了按钮单击事件中的代码,但我相信您已经了解了其意图
选项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);
};
我没有可用的测试responseStream功能的代码,但上面的代码将为您提供所需的响应。我使用的是Microsoft 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);
}
使用(var-httpClient=new-httpClient(handler))
{
任务contentsTask=httpClient.GetStringAsync(uri);
//等待!控件返回调用方,任务继续在另一个线程上运行
字符串内容=等待内容STASK;
vendors=Newtonsoft.Json.JsonConvert.DeserializeObject(内容);
}
我很确定你不能写等待var z
。另外,这里说的IAsyncResult
是不可等待的。那也不行IAsyncResult
是不可等待的。有趣的是,它既不适用于WP8,也不适用于Android。有趣的是,我将尝试一下。