Uploading Form Data

WebClient provides UploadValues methods for posting data to an HTML form.

Here's how to query the Safari website for books containing the term "WebClient":


using System;
using System.Net;
using System.Threading;

class ThreadTest
{
    static void Main()
    {
        WebClient wc = new WebClient();
        wc.Proxy = null;

        var data = new System.Collections.Specialized.NameValueCollection();
        data.Add("searchtextbox", "webclient");
        data.Add("searchmode", "simple");

        byte[] result = wc.UploadValues("http://my.safaribooksonline.com/search", "POST", data);
        System.IO.File.WriteAllBytes("SearchResults.html", result); 
        System.Diagnostics.Process.Start("SearchResults.html");

    }

}

Here's the previous example written with WebRequest:

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

    }

}
  
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.