1

我想执行一个QueryString使用 WebClient 但使用 POST 方法

这就是我到目前为止所得到的

代码:

using (var client = new WebClient())
{
    client.QueryString.Add("somedata", "value");
    client.DownloadString("uri");
}

它正在工作,但不幸的是它使用的是 GET 而不是 POST,我希望它使用 POST 的原因是我正在进行网络抓取,这就是我在 WireShark 中看到的请求的发出方式。[它使用 POST 作为一种方法,但没有 POST 数据,只有查询字符串。]

4

2 回答 2

1

这将帮助你,使用WebRequest而不是WebClient.

using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
class ThreadTest
{
    static void Main()
    {
        WebRequest req = WebRequest.Create("http://www.yourDomain.com/search");

        req.Proxy = null;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        string reqString = "searchtextbox=webclient&searchmode=simple"; 
        byte[] reqData = Encoding.UTF8.GetBytes(reqString); 
        req.ContentLength = reqData.Length;

        using (Stream reqStream = req.GetRequestStream())
            reqStream.Write(reqData, 0, reqData.Length);

        using (WebResponse res = req.GetResponse())
        using (Stream resSteam = res.GetResponseStream())
        using (StreamReader sr = new StreamReader(resSteam)) 
            File.WriteAllText("SearchResults.html", sr.ReadToEnd());

        System.Diagnostics.Process.Start("SearchResults.html");

    }

}
于 2013-07-07T19:01:41.757 回答
1

回答您的具体问题:

client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] response = client.UploadData("your url", "POST", new byte[] { });
//get the response as a string and do something with it...
string s = System.Text.Encoding.Default.GetString(response);

但是使用 WebClient 可以是一个 PITA,因为它不接受 cookie,也不允许您设置超时。

于 2013-07-07T19:22:17.063 回答