C#模拟Post和Get方式发送数据

分类: code | 标签: | 日期:

通过应用程序读取网页信息的时候,通常需要抓取网页的数据,但是有一个问题就是很多网页需要登录后才能够获得页面数据,那么就需要保存当前的 cookie,在.NET中可以使用CookieContainer 对象来保存登录后的Cookie信息,每次发送数据的时候加上Cookie信息,就可以解决这个问题了。

#region 同步通过POST方式发送数据
/// <summary>
/// 通过POST方式发送数据
/// </summary>
/// <param name=”Url”>url</param>
/// <param name=”postDataStr”>Post数据</param>
/// <param name=”cookie”>Cookie容器</param>
/// <returns></returns>
public string SendDataByPost(string Url,string postDataStr,ref CookieContainer cookie)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
if (cookie.Count == 0)
{
request.CookieContainer = new CookieContainer();
cookie = request.CookieContainer;
}
else
{
request.CookieContainer = cookie;
}

request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;
request.ContentLength = postDataStr.Length;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding(“gb2312″));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(“utf-8″));
string retString= myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();

return retString;
}
#endregion

#region 同步通过GET方式发送数据
/// <summary>
/// 通过GET方式发送数据
/// </summary>
/// <param name=”Url”>url</param>
/// <param name=”postDataStr”>GET数据</param>
/// <param name=”cookie”>GET容器</param>
/// <returns></returns>
public string SendDataByGET(string Url, string postDataStr, ref CookieContainer cookie)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url +( postDataStr == “” ? “” : “?”) + postDataStr);
if (cookie.Count == 0)
{
request.CookieContainer = new CookieContainer();
cookie = request.CookieContainer;
}
else
{
request.CookieContainer = cookie;
}

request.Method = “GET”;
request.ContentType = “text/html;charset=UTF-8″;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(“utf-8″));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();

return retString;
}
#endregion

声明:本文为耿师傅 http://www.bordf.com发布文章。转载务必注明出处

注意:转载须保留全文:请保留本文出处!否则耿师傅将向你网站的主机商投诉。
本文永久地址:http://www.bordf.com/article/285.html


表情:<( ̄︶ ̄)> | (⊙ˍ⊙) | >﹏< | b( ̄▽ ̄)d | (─.─||) | (^_-)

[ Ctrl+Enter提交 ]