Saturday, May 7, 2016

Các cách POST dữ liệu cơ bản trong C#





// Cách 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RegexTesting
{
    class Test
    {
        public void cuongvizut()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/codervizut");

            var postData = "username=hello";
            postData += "&password=world";
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //GET
            var request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/codervizut");

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
    }
}

//Cách 2: WebClient (Also now legacy)
using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["Thamso1"] = "Cuong";
    values["Thamso2"] = "Vizut";

    var response = client.UploadValues("https://www.facebook.com/codervizut", values);

    var responseString = Encoding.Default.GetString(response);
}
GET
using (var client = new WebClient())
{
    var responseString = client.DownloadString("https://www.facebook.com/codervizut");
}
//Cách 3: HttpClient

Hiện nay phương pháp ưa thích. Không đồng bộ. Thích hợp với .NET 4.5; phiên bản di động cho các nền tảng khác có sẵn thông qua NuGet.
using System.Net.Http;
POST
using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
       { "thamso1", "cuong" },
       { "thamso2", "vizut" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("https://www.facebook.com/codervizut", content);

    var responseString = await response.Content.ReadAsStringAsync();
}
GET
using (var client = new HttpClient())
{
    var responseString = client.GetStringAsync("https://www.facebook.com/codervizut");
}
<pre>
<code class="codepad language-csharp" data-codepad="theme:crimson_editor" style="width:100%;height:400px;" >//Cách 4: 3rd-Party Libraries
RestSharp
Thử nghiệm với bộ thư viện tại NuGet.
Flurl.Http
Đây là phương pháp mới mình chưa làm việc nhiều với nó cho lắm. Tải bản thu gọn tại NuGet.
using Flurl.Http;
POST
var responseString = await "https://www.facebook.com/codervizut"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();
GET
var responseString = await "https://www.facebook.com/codervizut"
    .GetStringAsync();</code>
</pre>
// Cách 5 :GET đơn giản nhất
using (var wb = new WebClient())
{
    var response = wb.DownloadString(url);
}
Cách POST đơn giản nhất nếu bạn không quan tâm tới cookie và header
using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["username"] = "myUser";
    data["password"] = "myPassword";

    var response = wb.UploadValues(url, "POST", data);
}
Cách 6: Cách sử lý bằng WebRequest
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main ()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes (postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream ();
            // Write the data to the request stream.
            dataStream.Write (byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close ();
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}

Cách 7: Phương thức đơn giản hay viết tools:
 public static string HttpPost(string URI, string Parameters) 
{
   System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   req.Proxy = new System.Net.WebProxy(ProxyString, true);
   //Add these, as we're doing a POST
   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   //We need to count how many bytes we're sending. 
   //Post'ed Faked Forms should be name=value&
   byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length); //Push it out there
   os.Close ();
   System.Net.WebResponse resp = req.GetResponse();
   if (resp== null) return null;
   System.IO.StreamReader sr = 
         new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}

Cách 8: Dùng chilkat dotnet
Chilkat.Global chilkatGlob = new Chilkat.Global();
bool success = chilkatGlob.UnlockBundle("Anything for 30-day trial.");
if (success != true) {
    Console.WriteLine(chilkatGlob.LastErrorText);
    return;
}

//  Imagine a URL that contains two params: one named "xyz" and one named "name".
//  We want to send a POST to it, but with 2 additional params in the body of the request.
//  The PostUrlEncoded method cannot be used because it parses the URL and puts all the params
//  in the HTTP body.  The SynchronousRequest method should instead be used so
//  that the req.Path can be explicitly specified.
string url = "http://www.chilkatsoft.com/echoPost.asp?xyz=123&name=matt";

Chilkat.Http http = new Chilkat.Http();

//  Provide a session log path so we can visually verify the exact request sent.
//  (This is only for debugging purposes.)
http.SessionLogFilename = "c:/aaworkarea/httpLog.txt";

//  Create an HTTP request that has two additional params
Chilkat.HttpRequest req = new Chilkat.HttpRequest();

req.HttpVerb = "POST";
req.Path = "/echoPost.asp?xyz=123&name=matt";
req.AddParam("sport","tennis");
req.AddParam("tournament","French Open");

//  Send the HTTP POST and get the response.
Chilkat.HttpResponse resp = http.SynchronousRequest("www.chilkatsoft.com",80,false,req);
if (resp == null ) {
    Console.WriteLine(http.LastErrorText);
    return;
}

Console.WriteLine(resp.BodyStr);

Console.WriteLine("Success.");

Bài Viết Liên Quan