目的:工作中已经两次使用了,特此记录一下,并写好注释
    /// <summary>
/// HttpWebRequest的基本配置
/// </summary>
public class HttpConfig
{
/// <summary>
/// 协议:http/https
/// </summary>
public string protocol
{
set;
get;
} /// <summary>
/// 发送端发送的数据格式
/// </summary>
public string contentType
{
set;
get;
} /// <summary>
/// 客户端希望接受的数据类型
/// </summary>
public string accept
{
set;
get;
} /// <summary>
/// 标识请求者的一些信息,如浏览器类型和版本、操作系统,使用语言等信息(IE,Firefox以“Mozilla/....”开头)
/// </summary>
public string userAgent
{
set;
get;
} /// <summary>
/// 超时时间
/// </summary>
public int timeOut
{
set;
get;
} /// <summary>
/// 请求body的编码类型:utf-8/gbk2312/gbk
/// </summary>
public string encoding
{
set;
get;
} /// <summary>
/// 请求方式:GET/POST
/// </summary>
public string method
{
set;
get;
} /// <summary>
/// 是否保持持续连接。默认为true
/// </summary>
public bool keepAlive
{
set;
get;
} /// <summary>
/// cookie集合
/// </summary>
public CookieContainer cc = null; /// <summary>
/// http header集合
/// </summary>
public WebHeaderCollection whc = null; public HttpConfig()
{
protocol = "http";
contentType = "application/xml;charset=utf-8";
accept = "application/xml";
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)";
timeOut = 15;
encoding = "utf-8";
method = "POST";
keepAlive = false;
} public HttpConfig(Dictionary<string, string> dctCookieKeyValus, string Domain, Dictionary<string, string> dctHeaderKeyValus)
: this()
{
GetCookieContainer(dctCookieKeyValus, Domain);
GetWebHeaderCollection(dctHeaderKeyValus);
} /// <summary>
/// 设置cookies
/// </summary>
/// <param name="dctKeyValus"></param>
/// <param name="Domain"></param>
public void GetCookieContainer(Dictionary<string, string> dctKeyValus, string Domain)
{
if (dctKeyValus.Count > 0)
{
cc = new CookieContainer();
foreach (string key in dctKeyValus.Keys)
{
Cookie cookie = new Cookie(key, dctKeyValus[key]);
cookie.Domain = "";
cc.Add(cookie);
}
}
} /// <summary>
/// 设置httpheaders
/// </summary>
/// <param name="dctKeyValus"></param>
public void GetWebHeaderCollection(Dictionary<string, string> dctKeyValus)
{
if (dctKeyValus.Count > 0)
{
whc = new WebHeaderCollection();
foreach (string key in dctKeyValus.Keys)
{
whc.Add(string.Format("{0}:{1}", key, dctKeyValus[key]));
}
}
}
} public class HttpRequestAndResponse
{
HttpConfig httpConfig = null; public HttpRequestAndResponse(HttpConfig httpconfig)
{
httpConfig = httpconfig;
} /// <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 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; /*HttpWebRequest的基本属性设置*************************************************************/
req.ProtocolVersion = HttpVersion.Version10;
req.UserAgent = httpConfig.userAgent;
req.KeepAlive = httpConfig.keepAlive;
req.Timeout = 1000 * httpConfig.timeOut;
req.Method = httpConfig.method;
req.Accept = httpConfig.accept;
req.ContentType = httpConfig.contentType; /*写入http头部信息*************************************************************************/
if (httpConfig.whc != null)
req.Headers = httpConfig.whc; /*cookie拼接*************************************************************/
if (httpConfig.cc != null)
req.CookieContainer = httpConfig.cc; /*写入requestXML***************************************************************************/
if (!string.IsNullOrEmpty(requestXML))
{
byte[] bytes = System.Text.Encoding.GetEncoding(httpConfig.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(httpConfig.encoding)))
{
response = resStreamReader.ReadToEnd();
}
}
}
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(httpConfig.encoding)))
{
errString += resStreamReader.ReadToEnd() + "\n";
resStreamReader.Close();
resStream.Close();
}
}
errString += "#end\n"; exceptionRes.Close();
}
catch (Exception e)
{
errString = e.ToString();
}
finally
{
if (res!= null)
{
res.Close();
res = null;
} if (req != null)
{
req.Abort();
req = null;
}
} return response;
}
}

  

HttpWebRequest,HttpWebResponse 使用的更多相关文章

  1. HttpWebRequest,HttpWebResponse的用法和用途

    1.用途:HettpWebRequest,HettpWebResponse用途和webServers的作用差不多,都是得到一个页面传过来的值.HttpWebRequest 2.用法:--------- ...

  2. C#获取网页内容 (WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

    获取网页数据有很多种方式.在这里主要讲述通过WebClient.WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容. 这里获取的是包括网页的所有信息 ...

  3. C#网页采集数据的几种方式(WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

    一.通过WebClient获取网页内容 这是一种很简单的获取方式,当然,其它的获取方法也很简单.在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域.大概写法如下 //M ...

  4. 【转】C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据

    http://blog.csdn.net/kingcruel/article/details/44036871 版权声明:本文为博主原创文章,未经博主允许不得转载. ================= ...

  5. MSDN中HttpWebRequest/HttpWebResponse用法

    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://home.cnblogs.com/u/weiweiboqi/ ...

  6. HttpWebRequest,HttpWebResponse C# 代码调用webservice,参数为xml

    先上调用代码 public static string PostMoths(string url, string Json) { System.Net.HttpWebRequest request; ...

  7. HttpWebRequest 和HttpWebResponse总结

    1. 总结 总结2 3. Code using System; using System.Collections.Generic; using System.Linq; using System.Te ...

  8. C#中HttpWebRequest与HttpWebResponse的使用方法

    关键字:C# HttpWebRequest HttpWebResponse HTTP GET POST 请求 这个类是专门为HTTP的GET和POST请求写的,解决了编码,证书,自动带Cookie等问 ...

  9. 【转】C#中HttpWebRequest的用法详解

    本文实例讲述了C#中HttpWebRequest的用法.分享给大家供大家参考.具体如下: HttpWebRequest类主要利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来 ...

随机推荐

  1. OTL调用Oracle存储过程

    OTL很早前用过,今天写东西要调存储过程,程序写完了,调试死活通不过,折腾了一早晨. 最后才发现错误,这里总结一下: 1.代码写的不规范. 有个参数后边少写了个“,”以至于总是抱错.而单独写的测试例子 ...

  2. 转载 VC轻松解析XML文件 - CMarkup类的使用方法

    VC轻松解析XML文件 - CMarkup类的使用方法http://www.cctry.com/thread-3866-1-1.html VC解析XML文件的工具有很多,CMarkup, tinyXM ...

  3. dockerfile mysql

    FROM centos6.6-mysql5.5:0.0.4 MAINTAINER syberos:wangmo RUN mv /etc/my.cnf /etc/my.cnf.bak ADD my.cn ...

  4. 关于一种fastjson的死循环情况记录

    最近在一次项目中,使用fastjson做接口转换中,碰到了一个Stack Overflow.发现在getxxx方法内如果再次嵌套使用fastjson作json转换,就会无限循环. 错误实例: clas ...

  5. 判断唯一约束是否是唯一的Unique

    //检查 唯一约束Name //检查 唯一约束Name int count = new BLL.Funcs().GetRecordCount(string.Format("Name={0}& ...

  6. (转)配置ORACLE 11g绿色版客户端和PLSQL环境

    本文转载自:http://my.oschina.net/jang/blog/83009 本方法是通过使用ORACLE官方提供的精简版客户端,即绿色免安装的客户端. 下载地址(此处提供的是官方各版本下载 ...

  7. mybatis 学习二 MyBatis简介与配置MyBatis+Spring+MySql

    1.2.2建立MySql数据库 在C:\Program Files\MySQL\MySQL Server 5.7\bin下面: 首先连接MySQL:        mysql  -u root -p ...

  8. [转]在 Windows 操作系统中的已知安全标识符(Sid security identifiers)

    安全标识符 (SID) 是用于标识安全主体或安全组在 Windows 操作系统中的可变长度的唯一值.常用 Sid 的 Sid 标识普通用户的一组或通用组.跨所有操作系统,它们的值保持不变. 此信息可用 ...

  9. 2015.3.2 VC++6制作非MFC dll以及VS2005、VS2010调用

    1.在VC6中新建工程,选择Win32 Dynamic-Link Libary,输入dll名称如 DLL2015 2.在类型选择中,选择第2项 A Simple Dll project OK 3.随后 ...

  10. Laravel 在 with 查询中只查询个别字段

    在使用 Laravel 的关联查询中,我们经常使用 with 方法来避免 N+1 查询,但是 with 会将目标关联的所有字段全部查询出来,对于有强迫症的我们来说,当然是不允许的. 这时候我们可以使用 ...