HttpWebRequest,HttpWebResponse 使用
Posted 出门遇贵人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpWebRequest,HttpWebResponse 使用相关的知识,希望对你有一定的参考价值。
public class HttpRequestAndResponse { private static readonly string protocol = "http"; private static readonly string contentType = "application/xml;charset=utf-8"; // Content-Type private static readonly string accept = "application/xml"; // Accept private static readonly string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"; // userAgent public HttpRequestAndResponse() { } /// <summary> /// 调过https验证 /// </summary> private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } public string RequestAndResponse(string url, string requestXML, ref string errString, string encoding = "utf-8", bool isPost = true, int timeOut = 15) { string response = ""; HttpWebRequest req = null; HttpWebResponse res = null; try { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); ServicePointManager.DefaultConnectionLimit = 200;//最大并发连接数 //如果写在配置文件里 app.config // <system.net> // <connectionManagement> // <!--表示把对任何域名的请求最大http连接数都设置为200--> // <add address = "*" maxconnection = "200" /> // </connectionManagement> //</system.net> req = WebRequest.Create(url) as HttpWebRequest; /*cookie拼接*************************************************************/ CookieContainer cc = new CookieContainer(); Cookie cName = new Cookie("name", ""); cName.Domain = ""; Cookie cPwd = new Cookie("pwd", ""); cPwd.Domain = ""; cc.Add(cName); cc.Add(cPwd); req.CookieContainer = cc; /*HttpWebRequest的基本属性设置*************************************************************/ req.ProtocolVersion = HttpVersion.Version10; req.UserAgent = userAgent; req.KeepAlive = false; req.Timeout = 1000 * timeOut; req.Method = isPost ? "POST" : "GET"; req.Accept = accept; req.ContentType = contentType; /*写入http头部信息*************************************************************************/ req.Headers.Add(string.Format("{0}:{1}", "", "")); /*写入requestXML***************************************************************************/ if (!string.IsNullOrEmpty(requestXML)) { byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML); if (bytes.Length > 0) { req.ContentLength = bytes.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bytes, 0, bytes.Length); reqStream.Close(); } } } /*HttpWebResponse获取服务器数据**************************************************************/ res = req.GetResponse() as HttpWebResponse; using (Stream resStream = res.GetResponseStream()) { using (StreamReader resStreamReader = new StreamReader(resStream, Encoding.GetEncoding(encoding))) { response = resStreamReader.ReadToEnd(); resStreamReader.Close(); resStream.Close(); } } } catch (WebException e) { HttpWebResponse exceptionRes = e.Response as HttpWebResponse; errString = "#Status-line\n"; string format = "protocolVersion:{0}\tstatusCode:{1}\tstatusDescription:{2}\n"; errString += string.Format(format, exceptionRes.ProtocolVersion, Convert.ToInt32(exceptionRes.StatusCode), exceptionRes.StatusDescription); errString += "#Header\n"; format = "num[{0}]:({1}:{2})\n"; for (int i = 0; i < exceptionRes.Headers.Count; i++) { errString += string.Format(format, i, exceptionRes.Headers.Keys[i], exceptionRes.Headers[i]); } errString += "#Body\n"; using (Stream resStream = exceptionRes.GetResponseStream()) { using (StreamReader resStreamReader = new StreamReader(resStream, Encoding.GetEncoding(encoding))) { errString += resStreamReader.ReadToEnd() + "\n"; resStreamReader.Close(); resStream.Close(); } } errString += "#end\n"; exceptionRes.Close(); } catch (Exception e) { errString = e.ToString(); } finally { if (req != null) { res.Close(); res = null; } if (req != null) { req.Abort(); req = null; } } return response; } }
目的:工作中已经两次使用了,特此记录一下,并写好注释
以上是关于HttpWebRequest,HttpWebResponse 使用的主要内容,如果未能解决你的问题,请参考以下文章
webrequest 和 httpwebrequest 有啥区别