Cách 1:
public string Post(string url, string data)
{
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim() + "\n";
}
trong đó data có dạng
string data = "param1=value1&parm2=value2";
Cách 2:
public static string HttpPost(string URI, string Parameters)
{
// Create a 'HttpWebRequest' object.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
CookieContainer cookieJar = new CookieContainer();
req.CookieContainer = cookieJar;
req.Referer = "http://captcha.chat.yahoo.com/go/captchat/";
req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6";
req.KeepAlive = true;
req.Referer = URI;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters);
req.ContentLength = bytes.Length;
Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
WebResponse resp = req.GetResponse();
if (resp == null) return null;
StreamReader sr = new StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
Note: Parameters in my method is the same as
str = "question=" & CaptChaQuestion & "&.intl=us&answer=" & CaptChaAnswer in VB
Cách 3:
using System;
using System.Net;
using System.Web;
using System.Collections;
using System.IO;
namespace WebRequestExample
{
class WebPostRequest
{
WebRequest theRequest;
HttpWebResponse theResponse;
ArrayList theQueryData;
public WebPostRequest(string url)
{
theRequest = WebRequest.Create(url);
theRequest.Method = "POST";
theQueryData = new ArrayList();
}
public void Add(string key, string value)
{
theQueryData.Add(String.Format("{0}={1}",key,HttpUtility.UrlEncode(value)));
}
public string GetResponse()
{
// Set the encoding type
theRequest.ContentType="application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters = String.Join("&",(String[]) theQueryData.ToArray(typeof(string)));
theRequest.ContentLength = Parameters.Length;
// We write the parameters into the request
StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
sw.Write(Parameters);
sw.Close();
// Execute the query
theResponse = (HttpWebResponse)theRequest.GetResponse();
StreamReader sr = new StreamReader(theResponse.GetResponseStream());
return sr.ReadToEnd();
}
}
class MainClass
{
public static void Main(string[] args)
{
WebPostRequest myPost = new WebPostRequest("http://www.dijksterhuis.org/test/post.php");
myPost.Add("keyword","void");
myPost.Add("data","hello&+-[]");
Console.WriteLine(myPost.GetResponse());
}
}
}
Cách 4:
public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
private string Url = string.Empty;
/// <summary>
/// number of seconds for timeout
/// </summary>
public int Timeout = 0;
/// <summary>
/// Url to post to
/// </summary>
public RemotePost(string url)
{
Url = url;
}
/// <summary>
/// Parameters to add to the post
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="value">parameter value</param>
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
/// <summary>
/// Posts data to server using POST method
/// </summary>
/// <returns></returns>
public string Post()
{
string postData = String.Empty;
int keyscount = Inputs.Keys.Count;
for (int i = 0; i < keyscount; i++)
postData += "&" + Inputs.Keys[i] + "=" + HttpUtility.UrlEncode(Inputs[Inputs.Keys[i]]);
if (postData.Length > 0)
postData = postData.Substring(1);
HttpWebRequest wr = WebRequest.Create(Url) as HttpWebRequest;
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter requestWriter = new StreamWriter(wr.GetRequestStream()))
{
requestWriter.Write(postData);
}
return GetResponse(wr);
}
/// <summary>
/// Posts data to server using GET method
/// </summary>
/// <returns></returns>
public string Get()
{
string postData = String.Empty;
int keyscount = Inputs.Keys.Count;
for (int i = 0; i < keyscount; i++)
postData += "&" + Inputs.Keys[i] + "=" + HttpUtility.UrlEncode(Inputs[Inputs.Keys[i]]);
if (postData.Length > 0)
postData = postData.Substring(1);
string postUrl = Url.Contains("?") ? (Url + "&" + postData) : (Url + "?" + postData);
HttpWebRequest wr = WebRequest.Create(postUrl) as HttpWebRequest;
wr.Method = "GET";
return GetResponse(wr);
}
private string GetResponse(HttpWebRequest wr)
{
wr.Timeout = Timeout * 1000; //millisecond timeout
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
return String.Empty;
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
return readerStream.ReadToEnd();
}
}
}
}
Cách sử dụng:
RemotePost req = new RemotePost(postUrl);
req.Timeout = 3;
req.Add("FirstName", "First");
req.Add("LastName", "Last");
string response = req.Post();
string response = req.Get();
Chúc vui