我在便携式项目中使用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
总是显示等于{{ 1}}。
我做错了什么?我已设置null
权限,并已验证Android模拟器可以访问互联网。
答案 0 :(得分:1)
我在Microsoft HTTP Client Libraries中使用它 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);
}
答案 1 :(得分:0)
啊,我明白了...我已经相应地编辑了答案。我已在基本的HTTP GET上对此进行了测试,并且它在所提供的两个示例中都有效。下面的示例显示了Button click事件中的代码,但我确信您有意图..
选项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功能,但上面的代码将为您提供所需的响应。