C# 下载指定参数的网页内容
C# Download webpage content with given parameters
我有问题。我试图获取我的网页的内容,所以我找到了这段代码:
WebClient client = new WebClient();
string downloadString = client.DownloadString("mysite.org/page.php");
但是我的 php 页面中有一些 $_POST
变量,那么如何将它们添加到页面的下载中呢?
你可以尝试这样的事情。不使用 webClient,而是使用 WebRequest 和 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://docs.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");
我有问题。我试图获取我的网页的内容,所以我找到了这段代码:
WebClient client = new WebClient();
string downloadString = client.DownloadString("mysite.org/page.php");
但是我的 php 页面中有一些 $_POST
变量,那么如何将它们添加到页面的下载中呢?
你可以尝试这样的事情。不使用 webClient,而是使用 WebRequest 和 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://docs.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");