0

I have a problem. I am trying to get the content of my webpage, so I found this code:

WebClient client = new WebClient();
string downloadString = client.DownloadString("mysite.org/page.php");

But I have a few $_POST variables in my php page, so how can I add them to the download of the page?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Convert the data you want to send into a bytearray and write it through the request stream. So instead of `webClient`, use `webRequest` – Joel Dec 22 '19 at 23:05
  • You might want to take a look into the documentation of the [`UploadString`](https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstring?view=netframework-4.8) method. – Markus Safar Dec 22 '19 at 23:05

1 Answers1

1

You could try something like this. Instead of using webClient, use WebRequest and WebResponse.

private string PostToFormWithParameters(string query)
{
    try
    {
        string url = "protocol://mysite.org/page.php/";
        string data = "?pageNumber=" + query; // data you want to send to the form.
        HttpWebRequest WebRequest = (HttpWebRequest)WebRequest.Create(url);
        WebRequest.ContentType = "application/x-www-form-urlencoded";
        byte[] buf = Encoding.ASCII.GetBytes(data);
        WebRequest.ContentLength = buf.Length;
        WebRequest.Method = "POST";    

        using (Stream PostData = WebRequest.GetRequestStream())
        {
            PostData.Write(buf, 0, buf.Length);
            HttpWebResponse WebResponse = (HttpWebResponse)WebRequest.GetResponse();
            using (Stream stream = WebResponse.GetResponseStream())
                using (StreamReader strReader = new StreamReader(stream))
                    return strReader.ReadLine(); // or ReadToEnd() -- https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=netframework-4.8                            
            WebResponse.Close();
       }

    }
    catch (Exception e)
    {
        /* throw appropriate exception here */
        throw new Exception();
    }
    return "";
}

...

var response = PostToFormWithParameters("5");
Joel
  • 5,732
  • 4
  • 37
  • 65
  • I think you misplaced the return at the end? Should it be in the catch? –  Dec 22 '19 at 23:36
  • And I get 2 errors on this line: `HttpWebRequest WebRequest = (HttpWebRequest)WebRequest.Create(url);` The first one is: "`use of unassigned local variable: 'WebRequest`".... And the second one is: "`Member 'WebRequest.Create(string)' cannot be accessed with an instance reference; qualify it with a type name instead`" –  Dec 22 '19 at 23:41
  • you have to import HttpWebRequest and HttpWebResponse in your file. – Joel Dec 22 '19 at 23:46
  • I already imported: `using System.Net;` ? –  Dec 22 '19 at 23:49