HTML into string from http address

G

Guest

Hi

What is the easiet way to get the HTML from an URL location into a string.

regards Jesper
 
P

PL

What is the easiet way to get the HTML from an URL location into a string.

Use the System.Net.WebClient:

private string GetUrl(string sUrl)
{
string sContent = null;

using (WebClient client = new WebClient())
{
try
{
client.Headers.Add("user-agent", "Mozilla/4.0
(compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

Stream data = client.OpenRead(sUrl);
StreamReader reader = new StreamReader(data);

sContent = reader.ReadToEnd();
}
catch (Exception e)
{
throw new System.Exception("Failed to fetch data
from URL: " + e.Message);
}
}

return ( ( sContent != null ? sContent : "" ) );
}

PL.
 
M

Michael Nemtsev

Hello Jesper,

J> What is the easiet way to get the HTML from an URL location into a

See code below

public static string GetHtmlFromUrl(string url)
{
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException("url","Parameter is null or empty");

string html = "";
HttpWebRequest request = GenerateHttpWebRequest(url);
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (VerifyResponse(response) == ResponseCategories.Success)
{
// Get the response stream.
Stream responseStream = response.GetResponseStream();
// Use a stream reader that understands UTF8.
using(StreamReader reader =
new StreamReader(responseStream, Encoding.UTF8))
{
html = reader.ReadToEnd();
}
}
}
return html;
}



---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top