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?

2
  • Convert the data you want to send into a bytearray and write it through the request stream. So instead of webClient, use webRequest Commented Dec 22, 2019 at 23:05
  • You might want to take a look into the documentation of the UploadString method. Commented Dec 22, 2019 at 23:05

1 Answer 1

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"); 
Sign up to request clarification or add additional context in comments.

4 Comments

I think you misplaced the return at the end? Should it be in the catch?
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"
you have to import HttpWebRequest and HttpWebResponse in your file.
I already imported: using System.Net; ?