Windows 8 c# -检索网页源作为字符串

本文关键字:字符串 网页 检索 Windows | 更新日期: 2023-09-27 18:18:37

有一个实际适用于Windows 8平台的XAML和c#教程: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 c# -检索网页源作为字符串

如果你正在为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();
}

也许他们已经在最新的API中弃用了close()。这应该可以工作:

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
using(WebResponse myResponse = myRequest.GetResponse() )
{
    using(StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8)) 
    {
        string result = sr.ReadToEnd();
    }
}

using命令将自动处置您的对象。

显示webnoob的注释:

只是指出(用于OP参考)您只能在实现IDisposable的类上使用using(在这种情况下是好的)

using System.Net;
using System.Net.Http;
var httpClient = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, targetURL);
//message.Headers.Add(....);
//message.Headers.Add(....);
var response = await httpClient.SendAsync(message);
if (response.StatusCode == HttpStatusCode.OK)
{
    //HTTP 200 OK
    var requestResultString = await response.Content.ReadAsStringAsync();
}

我建议使用HTTP客户端s. Microsoft HTTP客户端示例