首页 > 解决方案 > C# 下载具有给定参数的网页内容

问题描述

我有个问题。我正在尝试获取我网页的内容,所以我找到了这段代码:

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

但是我的php页面中有一些$_POST变量,那么如何将它们添加到页面的下载中?

标签: c#postwebclient

解决方案


你可以试试这样的。不要使用 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");

推荐阅读