简体   繁体   中英

POST Querystring using WebClient

I want to execute a QueryString using WebClient but using the POST Method

That is what I got so far

CODE:

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

It is working but unfortunately it is using GET not POST and the reason I want it to use POST is that I am doing a web scraping and this is how the request is made as I see in WireShark. [IT USES POST AS A METHOD BUT NO POST DATA ONLY THE QUERY STRING.]

this will help you, use WebRequest instead of 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");

    }

}

In answer to your specific question:

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);

But using WebClient can be a PITA since it doesn't accept cookies nor allow you to set a timeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM