views:

417

answers:

2

Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?

+5  A: 

You could use the System.Net.WebClient class of the .NET Framework. See the MSDN documentation here.

Simple example:

using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }

        WebClient client = new WebClient ();

        // Add a user agent header in case the 
        // requested URI contains a query.

        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 (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}

There are other useful methods of the WebClient, which allow developers to download and save resources from a specified URI.

The DownloadFile() method for example will download and save a resource to a local file. The UploadFile() method uploads and saves a resource to a specified URI.

UPDATE:

WebClient is simpler to use than WebRequest. Normally you could stick to using just WebClient unless you need to manipulate requests/responses in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx

splattne
what's the advantage of using WebClient for response and request methods versus WebRequest and WebResponse?
balexandre
For example methods like DownloadFile and UploadFile which simplify some common tasks.
splattne
I will try use WebClient next time then :) thanks for the inside
balexandre
What is a user agent header?
xoxo
Also, how would you go about getting the time it takes to finish retrieving data?
xoxo
@xoxo: for example you want that the server you are requesting data, things that you are using IE 6.0 instead a no-browser stuff, for the splattne example ;)
balexandre
@xoxo: is it only to get the time? use TimeSpan, get the current time before and after, then show the diff.
balexandre
Thanks alot guys! Although now, which is the better route to take/has more functionality, WebClient or WebRequest/Response?
xoxo
as splattne said... I will guess WebClient, but I don't know that object, I need to give it a try first before I say anything about it :)
balexandre
WebClient is more simple to use than WebRequest. Normally youcould stick to using just WebClient unless you need to manipulatethe request in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx
splattne
thxs for the link
balexandre
+6  A: 

what do you want to do?

send a request and grab the response in a String so you can process?

HttpWebRequest and HttpWebResponse will work

if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method

WebRequest and WebResponse

All the 4 methods above are in System.Net Namespace

If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with WCF (RESTfull style).

hope it helps you finding your way :)

as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.

case: send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:

private void btnSendRequest_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    try
    {
        String queryString = "user=myUser&pwd=myPassword&tel=+123456798&msg=My message";
        byte[] requestByte = Encoding.Default.GetBytes(queryString);

        // build our request
        WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/xml";
        webRequest.ContentLength = requestByte.Length;

        // create our stram to send
        Stream webDataStream = webRequest.GetRequestStream();
        webDataStream.Write(requestByte, 0, requestByte.Length);

        // get the response from our stream
        WebResponse webResponse = webRequest.GetResponse();
        webDataStream = webResponse.GetResponseStream();

        // convert the result into a String
        StreamReader webResponseSReader = new StreamReader(webDataStream);
        String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", "");

        // close everything
        webResponseSReader.Close();
        webResponse.Close();
        webDataStream.Close();

        // You now have the HTML in the responseFromServer variable, use it :)
        textBox1.Text = responseFromServer;
    }
    catch (Exception ex)
    {
        textBox1.Text = ex.Message;
    }
}

The code does not work cause the URL is fictitious, but you get the idea. :)

balexandre
Thanks, that helps alot. Although the queryString...that is the part in the URL that basically says the criteria you have searched for right? What if the website uses encoded ones or hides them altogether? Would this method work on just a home page?
xoxo
webRequest.ContentType = "application/x-www-form-urlencoded"; then you can add Headers to the request like webRequest.Headers.Add("myHeaderName", "myHeaderValue"); > remember to Add Headers before you call the Lenght! so it gives you the correct lenght of the request.
balexandre
all websites change, for example you can't do a POST in google or yahoo cause the server will give you: "The remote server returned an error: (405) Method Not Allowed." if you can ask, you will need to try several times until you get it right.
balexandre