There's A Hard Way & An Easy Way: Getting/Reading HTTP Responses
Yesterday, after somone asked on the forums how to do a web request in an application, I posted some code that I had written a while ago, and I got some great feedback on it. It solved a problem that I was working on, and did exactly what a few people have been asking for.
As it turns out, that was the hard way of doing things. If you don't count { } on separate lines, that took 9 lines of code. Someone yesterday pointed out how to do it in 4.
So I present to you, 4 lines:
public static string GetHTML(string url, string proxy)
{
System.Net.WebClient client = new WebClient();
if (!String.IsNullOrEmpty(proxy))
client.Proxy = proxy;
return client.DownloadString(new Uri(url));
}
The one difference on this, it that in the one from yesterday, I was able to put a timeout of 2.5 seconds. If the page hadn't downloaded in that, it failed. With the code I've posted today, there doesn't seem to be a method or property to set that value.
Comments
- Anonymous
March 03, 2006
Is this 2.0 specific? - Anonymous
March 03, 2006
PeteL demonstrated in his two recent blog entries something that i find myself doing far too often for... - Anonymous
March 05, 2006
I believe to set the proxy you should have
client.Proxy = new WebProxy(proxy, true); - Anonymous
March 07, 2006
Kizzer,
Yep, this is 2.0 specific. This was a feature that was added in the new version of the framework.