簡體   English   中英

使用 WebClient POST 查詢字符串

[英]POST Querystring using WebClient

我想使用 WebClient 但使用 POST 方法執行QueryString

這就是我到目前為止所得到的

代碼:

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

它正在工作,但不幸的是它使用的是 GET 而不是 POST,我希望它使用 POST 的原因是我正在進行網絡抓取,這就是我在 WireShark 中看到的請求的方式。 [它使用 POST 作為一種方法,但不只發布查詢字符串的數據。]

這將幫助您,使用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");

    }

}

回答您的具體問題:

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,也不允許您設置超時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM