您的位置:首页 > 理论基础 > 计算机网络

WEBHttpRequest

2014-01-17 09:21 246 查看
public string Url { get; set; }
public string Refer { get; set; }
public string Method { get; set; }
public string PostData { get; set; }
object obj = new object();

public WEBHttpRequest() { }
public WEBHttpRequest(string loginUrl, string refer, string method, string postData)
{
Url = loginUrl;
Refer = refer;
Method = method;
PostData = postData;
}

public void SendAutoDataToServer(Action<string> callback, bool IsKeepAlive, bool IsAllowAutoRedirect)
{
lock (obj)
{
HttpWebRequest httpWebRequest;
byte[] byteArray = Encoding.ASCII.GetBytes(PostData);

//基于apache服务器,IIS发布的则不需要
ServicePointManager.Expect100Continue = false;

//创建对url的请求
httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
httpWebRequest.Referer = Refer;

httpWebRequest.Accept = "*/*";
httpWebRequest.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/QVOD, application/QVOD, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-xpsdocument, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
httpWebRequest.Headers["Accept-Language"] = "zh-cn";
httpWebRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0;)";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.KeepAlive = IsKeepAlive;

httpWebRequest.Headers["Cache-Control"] = "no-cache";
httpWebRequest.AllowAutoRedirect = IsAllowAutoRedirect;
//协议方式
httpWebRequest.Method = Method;
httpWebRequest.Timeout = 20000;
//忽略证书
System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
{
return true;
};
//post开始
//请求内容长度
if (httpWebRequest.Method == "POST" || httpWebRequest.Method == "post")
{
try
{
httpWebRequest.ContentLength = byteArray.Length;

httpWebRequest.BeginGetRequestStream((a) =>
{
try
{
using (Stream datasStream = httpWebRequest.EndGetRequestStream(a))
{
datasStream.Write(byteArray, 0, byteArray.Length);
//异步返回html
httpWebRequest.BeginGetResponse((ar) =>
{
try
{
using (var webresponse = (HttpWebResponse)httpWebRequest.EndGetResponse(ar))
{
using (var stream = webresponse.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
callback(sr.ReadToEnd());
}
}
}
}
catch (Exception e) { callback(e.ToString()); }
finally { httpWebRequest.Abort(); }
}, null);
}
}
catch (Exception e) { callback(e.ToString()); return; }
}, null);
}
catch (Exception e) { callback(string.Empty); return; }

}
else
{
//异步返回html
httpWebRequest.BeginGetResponse((ar) =>
{
try
{
using (var webresponse = (HttpWebResponse)httpWebRequest.EndGetResponse(ar))
{
using (var stream = webresponse.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
callback(sr.ReadToEnd());
}
}
}
}
catch (Exception e) { callback(string.Empty); }
finally { httpWebRequest.Abort(); }
}, null);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: