Windows 8 C# – 将网页源检索为字符串
发布时间:2020-12-13 21:23:51 所属栏目:Windows 来源:网络整理
导读:有一个教程实际上适用于带有XAML和C#: http://www.tech-recipes.com/rx/1954/get_web_page_contents_in_code_with_csharp/的Windows 8平台 这是如何做: HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);myRequest.Method = "GET";WebR
有一个教程实际上适用于带有XAML和C#:
http://www.tech-recipes.com/rx/1954/get_web_page_contents_in_code_with_csharp/的Windows 8平台
这是如何做: HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL); myRequest.Method = "GET"; WebResponse myResponse = myRequest.GetResponse(); StreamReader sr = new StreamReader(myResponse.GetResponseStream(),System.Text.Encoding.UTF8); string result = sr.ReadToEnd(); sr.Close(); myResponse.Close(); 但是在Windows 8中,最后两行是关闭连接的代码(我假设),检测到错误.尽管如此,它在没有关闭连接的情况下工作正常,但有什么可能性?为什么我们必须关闭连接?如果我不这样做可能会出错? “关闭连接”甚至意味着什么?
如果您正在为Windows 8开发,则应考虑使用异步方法来提供更好的用户体验,这是推荐的新标准.您的代码将如下所示:
public async Task<string> MakeWebRequest(string url) { HttpClient http = new System.Net.Http.HttpClient(); HttpResponseMessage response = await http.GetAsync(url); return await response.Content.ReadAsStringAsync(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- powershell – 在Nano Server上运行Service Fabr
- 使用Skype API的Java bot
- iis-7 – IIS 7是否具有同时请求的限制?
- 软件将Windows通知事件日志发送到linux syslog服
- windows-server-2008 – 跨海访问文件共享(通过V
- 使用Wix卸载MSI之前的自定义操作
- windows server 2012 用sysdba登录报错 ORA-0103
- windows-7 – 在Windows 7中是否有完全支持Torto
- windows-phone-7 – 是否有更简单快速的方法来检
- windows server 2008 AD与DNS服务器配置时注意的
热点阅读