有一个教程实际上适用于带有 XAML 和 C# 的 Windows 8 平台:http://www.tech-recipes.com/rx/1954/get_web_page_contents_in_code_with_csharp/
方法如下:
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();
}
关于c# - Windows 8 C# - 以字符串形式检索网页源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17107182/