简体   繁体   中英

Windows 8 C# - retrieve a webpage source as string

there's a tutorial that actually works for Windows 8 platform with XAML and C#: http://www.tech-recipes.com/rx/1954/get_web_page_contents_in_code_with_csharp/

Here's how:

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();

However in Windows 8, the last 2 lines which are code to close the connection (I assume), detected error. It works fine without closing the connection, though, but what are the odds? Why do we have to close the connection? What could go wrong if I don't? What do "closing connection" even mean?

If you are developing for Windows 8, you should consider using asynchronous methods to provide for a better user experience and it is the recommend new standard. Your code would then look like:

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();
}

Maybe they've deprecated close() in the latest API. This should work:

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();
    }
}

The using command will automatically dispose your objects.

To highlight webnoob's comment:

Just to point out (for OP reference) you can only use using on classes that implement IDisposable (which in this case is fine)

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();
}

I would recommend using the HTTP Client s. Microsoft HTTP Client Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM