110,536
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 模拟POST访问
/// </summary>
/// <param name="postUrl">模拟POST的URL</param>
/// <param name="postDataStr">需要POST的数据</param>
/// <returns>模拟访问的网页源代码</returns>
public static string sendPost(string postUrl, string postDataStr)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 100;
System.Net.ServicePointManager.Expect100Continue = false;
string retString = string.Empty;
if (Global.noException)
{
//用来存放cookie
CookieContainer cookie = null;
HttpWebRequest request = null;
Stream myRequestStream = null;
HttpWebResponse response = null;
Stream myResponseStream = null;
StreamReader myStreamReader = null;
try
{
//转化
byte[] byteArray = Encoding.UTF8.GetBytes(postDataStr);
cookie = new CookieContainer();
//发送一个POST请求
request = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
request.CookieContainer = cookie;
request.Timeout = 3000;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
myRequestStream = request.GetRequestStream();
myRequestStream.Write(byteArray, 0, byteArray.Length);
myRequestStream.Close();
//获取返回的内容
response = (HttpWebResponse)request.GetResponse();
response.Cookies = cookie.GetCookies(response.ResponseUri);
myResponseStream = response.GetResponseStream();
myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
retString = myStreamReader.ReadToEnd();
}
catch (Exception ex)
{
Global.noException = false;
MessageBox.Show("发送POST失败!\n报错:" + ex.Message);
if (Login.IsConnectedInternet())
{
HtmlTool.SendGet(Global.downUrl);
}
}
finally
{
if (myStreamReader != null)
{
myStreamReader.Close();
}
if (myResponseStream != null)
{
myResponseStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
return retString;
}