2

So I thought it's time for me to learn C#, be easy with me guys, I'm very new to this.

I'm trying to create a very simple application (I'm using Windows Forms Application). My goal is:

  1. Using "GET" method, get the web page
  2. Read a text field (this value changes every time that the user is accessing the page
  3. Using "POST" method, send some values accordingly

Here is my code so far:

  private void button2_Click(object sender, EventArgs e)
{
    string URI = "http://localhost/post.php";
    string myParameters = "field=value1&field2=value2";

    using (WebClient wc = new WebClient())
    {
        string getpage = wc.DownloadString("http://localhost/post.php");
        MessageBox.Show(getpage);
        wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        string HtmlResult = wc.UploadString(URI, myParameters);
        MessageBox.Show(HtmlResult);
    }
}

So far so good, It's working but it's not entirely what I want to achieve here. I'm able to use POST method, but how do I use GET before sending the data? I want to send data according to GET result.

Please let me know if I should be giving a better description to what I'm trying to do.

Thanks.

Edit
This is my PHP Code:

<?php

    $a = session_id();

    if(empty($a))
        session_start();

        echo "Session: ".session_id()."<br/>\n";

Now, back to my C# code, I get different session ID in the two messages

user3800799
  • 534
  • 1
  • 5
  • 18
  • Have you tried the [download methods](http://msdn.microsoft.com/en-us/library/System.Net.WebClient_methods(v=vs.110).aspx)? Though your point #2 is a bit confusing. What is the ultimate goal for reading the page for a user's input. If the user inputs data don't you have it in a db? – scrappedcola Oct 10 '14 at 21:28

3 Answers3

16

Reading data with GET

Please refer to this answer: Easiest way to read from a URL into a string in .NET

using(WebClient client = new WebClient()) {
    string s = client.DownloadString(url);
}

Sessions

By default WebClient does not use any Session. So every call is handled as if you created a new Session. To do that you need something like this:

Please refer to these answers:

  1. Using CookieContainer with WebClient class

  2. Reading Response From URL using HTTP WEB REQUEST

Example code

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}

// ...

private void button2_Click(object sender, EventArgs e)
{
    string URI = "http://localhost/post.php";
    string myParameters = "field=value1&field2=value2";

    using (WebClient wc = new CookieAwareWebClient())
    {
        string getpage = wc.DownloadString("http://localhost/post.php");
        MessageBox.Show(getpage);
        wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        string HtmlResult = wc.UploadString(URI, myParameters);
        MessageBox.Show(HtmlResult);
    }
}
Tuan
  • 893
  • 1
  • 9
  • 24
  • 1
    I think he's asking how to use the GET functionality in the WebClient class, so he can get data and then craft a POST based on it. – pseudocoder Oct 10 '14 at 21:23
  • I wonder if that will work.. because they need to occur at the same session. Edit: pseudocoder, exactly my goal here. – user3800799 Oct 10 '14 at 21:23
  • Hi guys, im still not able to figure this one out. It still counts as a different session. Maybe the best comparison would be our browser (Chrome for example). You open a page, then you submit the form that's inside of it. without refreshing or anything – user3800799 Oct 10 '14 at 21:59
  • 1
    Did you read my second link about sessions? You have to setup the client properly to use a CookieContainer to handle sessions. – Tuan Oct 10 '14 at 22:02
  • Hi Tuan, I did read it but I couldn't get anything work. I'm working with session, not cookies. im editing my main post, look at the PHP code – user3800799 Oct 10 '14 at 22:20
  • 2
    To use sessions you have to use cookies. When you access an url, a session is created. The SessionId is provided as a cookie. Your client needs to save this cookie and send it the next time, so that your session can be resumed. If you use the Client in my 2nd link your requests should work with cookies and therefore resuming your session. – Tuan Oct 10 '14 at 22:22
  • thank you so much, you have no idea how much I appreciate this. thank you for your time Tuan! best answer I could imagine. – user3800799 Oct 11 '14 at 01:22
3

The GET method is really nothing but the parameters passed through the address line, just send your request to string.Format("{0}?{1}", URI, myParameters) (or URI + "?" + myParameters) and simply read response.

nurchi
  • 770
  • 11
  • 24
  • I imagine this would depend on your `PHP` script. The way I understood your question is that you want to send some data to the page using a combination of `GET` and `POST` methods. If this is the case, I don't see why this would not be in the same session. But if you want to send something via `GET`, then based on response from the page craft another request using `POST`, I believe this would be a separate request. If by session you mean session in the same sense as in the browser, there is a way to handle that (cookies and what not), but if don't remember off top of my head... – nurchi Oct 10 '14 at 21:30
  • I edited my main post check it out if you can guess where the problem is – user3800799 Oct 10 '14 at 22:25
0

I know its an long time ago but :

       byte[] readedData = null;

        await Task.Run(async() =>
        {
            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += (obj, args) => progessChangedAction?.Invoke(args.ProgressPercentage);

                readedData = await client.DownloadDataTaskAsync(requestUri).ConfigureAwait(false);
            }
        });

        return readedData;

}

Fai
  • 1