c# - C# 下载具有给定参数的网页内容
问题描述
我有个问题。我正在尝试获取我网页的内容,所以我找到了这段代码:
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");
推荐阅读
- google-apps-script - 自动清除范围
- javascript - SVG 颜色填充无法使用 JavaScript
- java - Firebase,com.google.firebase:firebase-messaging:17.3.0 不工作
- java - 在 webview 的 WebBackForwardList 中插入 url
- ruby-on-rails - 在使用设计保存之前设置模型
- mongodb - 蒙哥。使用一个数组查询文档,其子元素都必须匹配一个查询
- python - 没有为对象类型命名为 1 的轴
- java - 使用java 8中的lambda函数获取ArrayList的总数,根据日期分组
- javascript - 如何将文本和图像发布到 Facebook 页面?
- java - Recycleview 不从 json url 加载图像