原文:http://blog.csdn.net/haitaofeiyang/article/details/18362225

申公前几日和一个客户做系统对接,以前和客户对接一般采用webservice或者json 解析的方式,直接调用标准解析就可以。没想到客户用“请求响应模式”,直接访问人家的接口地址取数据,无奈打造一个通用的访问类吧

参考MSDN的解释:

HttpWebRequest类:提供WebRequest类的Http特定的实现。

HttpWebRequest 类对 WebRequest 中定义的属性和方法提供支持,也对使用户能够直接与使用 HTTP 的服务器交互的附加属性和方法提供支持。

不要使用构造函数创建HttpWebRequest实例,请使用System.Net.WebRequest.Create(URI uriString)来创建实例,如果URI是Http://或Https://, 
返回的是HttpWebRequest对象。(建立请求特定URI的对象) 
当向资源发送数据时,GetRequestStream方法返回用于发送数据的Stream对象。(获取请求数据的流对象) 
GetResponse方法向RequestUri属性指定的资源发出同步请求并返回包含该响应的HttpWebResponse。(获取来自internet的响应)

好了,直接上代码:

using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Windows.Forms; /*
* 作者:申公
* 日期:
* 说明:此类提供http,POST和GET访问远程接口
* */
namespace ZJS.EDI.Business.HttpUtility
{
/// <summary>
/// 有关HTTP请求的辅助类
/// </summary>
public class HttpWebResponseUtility
{ private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";//浏览器
private static Encoding requestEncoding = System.Text.Encoding.UTF8;//字符集 /// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
} /// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponse(string url, string parameters, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
} HttpWebRequest request = null;
Stream stream = null;//用于传参数的流 try
{
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
//创建证书文件
System.Security.Cryptography.X509Certificates.X509Certificate objx509 = new System.Security.Cryptography.X509Certificates.X509Certificate(Application.StartupPath + @"\\licensefile\zjs.cer");
//添加到请求里
request.ClientCertificates.Add(objx509);
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
} request.Method = "POST";//传输方式
request.ContentType = "application/x-www-form-urlencoded";//协议
request.UserAgent = DefaultUserAgent;//请求的客户端浏览器信息,默认IE
request.Timeout = 6000;//超时时间,写死6秒 //随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
} //如果需求POST传数据,转换成utf-8编码
byte[] data = requestEncoding.GetBytes(parameters);
request.ContentLength = data.Length; stream = request.GetRequestStream();
stream.Write(data, 0, data.Length); stream.Close();
}
catch (Exception ee)
{
//写日志
//LogHelper.
}
finally
{
if (stream != null)
{
stream.Close();
}
} return request.GetResponse() as HttpWebResponse;
} //验证服务器证书回调自动验证
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
} /// <summary>
/// 获取数据
/// </summary>
/// <param name="HttpWebResponse">响应对象</param>
/// <returns></returns>
public static string OpenReadWithHttps(HttpWebResponse HttpWebResponse)
{
Stream responseStream = null;
StreamReader sReader = null;
String value = null; try
{
// 获取响应流
responseStream = HttpWebResponse.GetResponseStream();
// 对接响应流(以"utf-8"字符集)
sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
// 开始读取数据
value = sReader.ReadToEnd();
}
catch (Exception)
{
//日志异常
}
finally
{
//强制关闭
if (sReader != null)
{
sReader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
if (HttpWebResponse != null)
{
HttpWebResponse.Close();
}
} return value;
} /// <summary>
/// 入口方法:获取传回来的XML文件
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static string GetResultXML(string url, string parameters, CookieCollection cookies)
{
return OpenReadWithHttps(CreatePostHttpResponse(url, parameters, cookies));
} }
}

调用实例:

/// 调用主程序
/// </summary>
public class Program
{ static string strUrlPre = ; // 测试环境Url
static string strKey = ;// 签名密钥
static string strMethod = ;// 方法编号 static void Main(string[] args)
{
//MessageBox.Show("请注意,马上将进行保存操作!"); StringBuilder sbRequestData =;//请求参数 // 发送请求
StringBuilder sbUrl = new StringBuilder(); // 请求URL内容
sbUrl.Append(strUrlPre);
sbUrl.Append("?");
sbUrl.Append("sign=" + strKeyMD5);
sbUrl.Append("&" + sbSystemArgs.ToString()); String strUrl = sbUrl.ToString();
//解析xml文件
string resultXML = HttpWebResponseUtility.GetResultXML(sbUrl.ToString(), sbRequestData.ToString(), null); }
}

HttpWebRequest和HttpWebResponse的更多相关文章

  1. C# HttpWebRequest与HttpWebResponse详解

    C# HttpWebRequest与HttpWebResponse详解  http://www.codeproject.com/Articles/6554/How-to-use-HttpWebRequ ...

  2. 使用HttpWebRequest以及HttpWebResponse读取Http远程文件

     主页>杂项技术>.NET(C#)> 使用HttpWebRequest以及HttpWebResponse读取Http远程文件 jackyhwei 发布于 2010-08-15 21: ...

  3. HttpWebRequest和HttpWebResponse用法小结

    http://www.cnblogs.com/willpan/archive/2011/09/26/2176475.html http://www.cnblogs.com/lip0121/p/4539 ...

  4. 利用HttpWebRequest和HttpWebResponse获取Cookie

    之前看过某个同学的一篇有关与使用JSoup解析学校图书馆的文章,仔细一看,发现竟然是同校!!既然对方用的是java,那么我也就来个C#好了,虽然我的入门语言是java. C#没有JSoup这样方便的东 ...

  5. c# HttpWebRequest与HttpWebResponse 绝技(转载)

    c# HttpWebRequest与HttpWebResponse 绝技    如果你想做一些,抓取,或者是自动获取的功能,那么就跟我一起来学习一下Http请求吧.本文章会对Http请求时的Get和P ...

  6. C#模拟POST提交表单(二)--HttpWebRequest以及HttpWebResponse

    上次介绍了用WebClient的方式提交POST请求,这次,我继续来介绍用其它一种方式 HttpWebRequest以及HttpWebResponse 自认为与上次介绍的WebClient最大的不同之 ...

  7. C# 利用 HttpWebRequest 和 HttpWebResponse 模拟登录有验证码的网站

    原文:C# 利用 HttpWebRequest 和 HttpWebResponse 模拟登录有验证码的网站 我们经常会碰到需要程序模拟登录一个网站,那如果网站需要填写验证码的要怎样模拟登录呢?这篇文章 ...

  8. 利用HttpWebRequest和HttpWebResponse获取Cookie并实现模拟登录

    利用HttpWebRequest和HttpWebResponse获取Cookie并实现模拟登录 tring cookie = response.Headers.Get("Set-Cookie ...

  9. C# -- HttpWebRequest 和 HttpWebResponse 的使用

    C# -- HttpWebRequest 和 HttpWebResponse 的使用 结合使用HttpWebRequest 和 HttpWebResponse,来判断一个网页地址是否可以正常访问. 1 ...

  10. C#使用HttpWebRequest和HttpWebResponse上传文件示例

    C#使用HttpWebRequest和HttpWebResponse上传文件示例 1.HttpHelper类: 复制内容到剪贴板程序代码 using System;using System.Colle ...

随机推荐

  1. 素数个数统计——Eratosthenes筛法 [LeetCode 204]

    1- 问题描述 Count the number of prime numbers less than a non-negative number, n 2- 算法思想 给出要筛数值的范围 $n$,找 ...

  2. 在线生成ICO图标、站标

    网上一搜有很多,找了两个比较好用的,分别是http://ico.storyren.com/和http://www.ico.la/,前面的那个好像更好点.上传png.jpg.或gif格式的图片,按自己需 ...

  3. 孤岛能源安卓游戏android源码

    孤岛能源是一个以孤岛为背景的模拟动作游戏,游戏中你的角色是 Android 机器人,目的是找到该岛上充满能量的能源造福人类.游戏中,你可以选择按键操作,也可以选择触摸操作.希望你能顺利完成任务.   ...

  4. windows phone 8 开发系列(一)环境搭建

    一:前奏说明 本人一名普通的neter,对新玩意有点小兴趣,之前wp7出来的时候,折腾学习过点wp7开发,后来也没怎么用到(主要对微软抛弃wp7的行为比较不爽),现在wp8已经出来一段时间了,市场上也 ...

  5. 《RHEL6.3权限的管理》

    变换用户身份    su 命令 从普通用户切换到root用户需要密码,从root用户切换到普通用户不需要密码. 这样的切换只是登陆的身份变为了root,文件的环境仍然没变.  su -命令 完全切换 ...

  6. ●linux进程的查看与操作●

    查看进程:ps -le | more ,ps -aux | more ,ps & 后台运行  jobs 查看后台进程  fg [n]调到前台  bg放到后台 ctrl +c 终止  ctrl ...

  7. 通过获取客户端Json数据字符串,反序列化为实体对象的一段代码

    #region 保存候选人数据 /// <summary> /// 保存候选人数据 /// </summary> /// <param name="entity ...

  8. WPF自定义控件(二)——TextBox

    和之前一样,先来看看效果: 这个TextBox可设置水印,可设置必填和正则表达式验证. 验证?没错,就是验证! 就是在输入完成后,控件一旦失去焦点就会自动验证!会根据我开放出来的“是否可以为空”属性进 ...

  9. int main(int argc,char* argv[])参数详解

    argc是命令行总的参数个数 argv[]是argc个参数,其中第0个参数是程序的全名,以后的参数 命令行后面跟的用户输入的参数,比如: int main(int argc, char* argv[] ...

  10. Fat-tree 胖树交换网络

    胖树架构下,网络带宽不收敛 传统的树形网络拓扑中,带宽是逐层收敛的,树根处的网络带宽要远小于各个叶子处所有带宽的总和. 而胖树网络则更像是真实的树,越到树根,枝干越粗,即:从叶子到树根,网络带宽不收敛 ...