Winfrom通过HttpWebRequest 发送Http请求Post、Get方法举例
C#篇章
添加引用 using System.Net; using System.Web;
代码一(Post方法举例)
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=" + strId;
postData += ("&password=" + strPassword);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string content = reader.ReadToEnd();
Console.WriteLine(content);
代码二(获得上面Post请求的Cookie值方便在get方式时调用)
关于Cookie以及Session的概念、自行百度
CookieContainer cc=request.CookieContainer
public static string GetAllCookies(CookieContainer Cookie)
{
string cookieValue = "";
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
foreach (object pathList in table.Values)
{
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
foreach (CookieCollection colCookies in lstCookieCol.Values)
foreach (Cookie c in colCookies)
{
Console.WriteLine(c.Domain + ":" + c.Name + "____" + c.Value + "\r\n");
Console.WriteLine(c.Value);
cookieValue = c.Value;
}
}
return cookieValue;
}
代码三(get方法举例)
string cookieStr = "shiroCookie="+GetAllCookies(request.CookieContainer);
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Cookie", cookieStr);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
MessageBox.Show(content);
以上是我对C#winfrom技术实现Http请求的个人见解、大家可以参考、有问题的可以留言一起讨论