tags:

views:

194

answers:

3

In a project I'm invovled in, there is a requirment that the price of certain stocks will be queryed from some web interface and be displayed in some way.

I know the "query" part of the requirment can be easily implemented using a Perl module like LWP::UserAgent. But for some reason, C# has been chosen as the language to implement the Display part. I don't want to add any IPC (like socket, or indirectly by database) into this tiny project, so my question is there any C# equivalent to the Perl's LWP::UserAgent?

+3  A: 

I'm not sure, but are you simply trying to make an HTTP Request? If so, you can use the HttpWebRequest class. Here's an example http://www.csharp-station.com/HowTo/HttpWebFetch.aspx

ChrisDiRulli
+6  A: 

You can use the System.Net.HttpWebRequest object.

It looks something like this:

// Setup the HTTP request.
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");

// This is optional, I'm just demoing this because of the comments receaved.
httpWebRequest.UserAgent = "My Web Crawler"; 

// Send the HTTP request and get the response.
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

if (httpWebResponse.StatusCode == HttpStatusCode.OK)
{
    // Get the HTML from the httpWebResponse...
    Stream responseStream = httpWebResponse.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    string html = reader.ReadToEnd();
}
dukk
Isn't HttpWeb redundant?
Schwern
Yeah it is, you could just do WebRequest.Create(...). I personally like to be more explicit since you can also do FtpWebRequest etc. Normally I also cast the WebRequest and WebResponse's to HttpWebRequest and HttpWebResponse as well. This will give you more functionality on your request/response (like changing the user agent).
dukk
I updated my code sample to be more useful for a real scenario.
dukk
Your code does not compile.. you need to change webRequest.GetResponse() to httpWebRequest.GetResponse()
0A0D
My bad, it's fixed now. Thanks!
dukk
I know this also just a simple example, but if it is a large web page, then reader.ReadtoEnd() will block.. suggestion for future readers is to place code into a thread class or backgroundWorkerThread
0A0D
@Roboto, you could also change that to ReadLine() or read to a buffer and it would help with that. There are also other methods in that snippet that will block you would want to change if you’re concerned about that. Like httpWebRequest.GetResponse() could be changed to BeginGetResponse() and EndGetResponse().
dukk
+2  A: 

If you want to simply fetch data from the web, you could use the WebClient class. It seems to be quite good for quick requests.

Daniel Bruce