C#模拟Http与Https请求框架实例

时间:2022-03-22 02:52:09
 using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace WebRequestTest
{
/// <summary>
/// 动态类,每个实例使用单独session
/// </summary>
public class HttpHelperNew
{
public CookieContainer cookie = new CookieContainer();
/// <summary>
/// post请求返回html
/// </summary>
/// <param name="Url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
//request.AllowAutoRedirect = false; //禁止自动重定向
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
request.CookieContainer = cookie; //cookie信息由CookieContainer自行维护
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = null;
try
{
this.SetCertificatePolicy();
response = (HttpWebResponse)request.GetResponse();
}
catch (System.Exception ex)
{
}
//获取重定向地址
//string url1 = response.Headers["Location"];
if (response !=null)
{
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
else
{
return "error"; //post请求返回为空
}
}
/// <summary>
/// get请求获取返回的html
/// </summary>
/// <param name="Url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public string HttpGet(string Url, string Querydata)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (Querydata == "" ? "" : "?") + Querydata);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.CookieContainer = cookie;
this.SetCertificatePolicy();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// response.Cookies = cookie.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
/// <summary>
/// 获得响应中的图像
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public Stream GetResponseImage(string url)
{
Stream resst = null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = true;
req.Method = "GET";
req.AllowAutoRedirect = true;
req.CookieContainer = cookie;
req.ContentType = "application/x-www-form-urlencoded";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Timeout = ;
Encoding myEncoding = Encoding.GetEncoding("UTF-8");
this.SetCertificatePolicy();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
resst = res.GetResponseStream();
return resst;
}
catch
{
return null;
}
}
/// <summary>
/// 正则获取匹配的第一个值
/// </summary>
/// <param name="html"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public string getStringByRegex(string html,string pattern)
{
Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matchs = re.Matches(html);
if (matchs.Count > )
{
return matchs[].Groups[].Value;
}
else
return "";
}
/// <summary>
/// 正则验证返回的response是否正确
/// </summary>
/// <param name="html"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public bool verifyResponseHtml(string html ,string pattern)
{
Regex re = new Regex(pattern);
return re.IsMatch(html);
}
//注册证书验证回调事件,在请求之前注册
private void SetCertificatePolicy()
{
ServicePointManager.ServerCertificateValidationCallback
+= RemoteCertificateValidate;
}
/// <summary>
/// 远程证书验证,固定返回true
/// </summary>
private static bool RemoteCertificateValidate(object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
return true;
}
}
}

C#模拟Http与Https请求框架实例的更多相关文章

  1. 模拟http或https请求,实现ssl下的bugzilla登录、新增BUG,保持会话以及处理token

    1.增加相应httpclient 需要的jar包到工程,如果是maven工程请在pom.xml增加以下配置即可: <dependency> <groupId>org.apach ...

  2. &period;net 模拟登陆 post https 请求跳转页面

    AllowAutoRedirect property is true, the Referer property is set automatically when the request is re ...

  3. Volley框架支持HTTPS请求。

    第一次写帖子,嘿嘿. 最近了解到google2013IO大会出了个网络框架,正好项目也需要用到,就看了下. 最后发现接口都是HTTPS的,但是Volley默认是不支持HTTPS,网上找了好久,都没有对 ...

  4. Android网络请求框架AsyncHttpClient实例详解&lpar;配合JSON解析调用接口&rpar;

    最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所 ...

  5. java中模拟http&lpar;https&rpar;请求的工具类

    在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应.比如我们想访问微信接口,获取其返回信息. 在 ...

  6. php封装curl&comma;模拟POST和GET请求HTTPS请求

    <?php /** * @title 封装代理请求 * @author victor **/ class ApiRequest { /** * curl提交数据 * @param String ...

  7. Google Volley框架之https请求

    先插一句.Google出的volley框架本身是支持https请求的,可是仅仅是针对有第三方机构认证过的. 假设自己随便在网上搞的一个证书,那volley是不支持请求的. 本文讲下怎样让volley支 ...

  8. PHP-Curl模拟HTTPS请求

     使用PHP-Curl方式模拟HTTPS请求,测试接口传参和返回值状态   上代码!! <?php /** * 模拟post进行url请求 * @param string $url * @par ...

  9. PHP&colon; 手把手编写自己的 MVC 框架实例教程

    1 什么是MVC MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model).视图(View)和控制器(Controller ...

随机推荐

  1. getchar&lpar;&rpar; 和 scanf&lpar;&quot&semi;&percnt;c&quot&semi;&rpar;的区别

    getchar()和scanf("%c")的功能都是从STDIN读一个字符,单论功能两者没有区别. 但两者的返回值是有区别的: -------------------------- ...

  2. 【JNI】C向C&plus;&plus;改造

    步骤: 1. 把c文件后缀名换成cpp2. Android.mk文件中的hello.c也要换成hello.cpp3. c++的使用的环境变量结构体中,访问了c使用的结构体的函数指针,函数名全部都是一样 ...

  3. php 通过PATH&lowbar;SEPARATOR判断当前服务器系统类型

    PATH_SEPARATOR是php中的一个预定义常量,我们可以直接echo这个常量,在linux系统中,该常量输出":",在windows系统中,该常量输出";&quo ...

  4. CentOS 6&period;x版本升级Mysql

    首先确定一下自己的DNS  vi /etc/resolv.conf    我一般为114.114.114.114 #-----------------------------CentOS 6.x版本升 ...

  5. 面试题之——抽象类(abstract class)与接口&lpar;interface&rpar;的区别

    抽象类可以有构造方法,接口中不能有构造方法.(虽然抽象类有构造方法,但它也不能被实例化) 抽象类中可以有普通成员变量,接口中没有普通成员变量. 抽象类和接口中都可以包含静态成员变量.抽象类中的静态成员 ...

  6. poj2823一道纯单调队列

    Sliding Window Time Limit: 12000MS   Memory Limit: 65536K Total Submissions: 32099   Accepted: 9526 ...

  7. RunLoop已入门?赶紧来应用一下

    前言 对RunLoop还没有什么概念的同学请移步我的上一篇文章,传送门:RunLoop入门 看我就够了http://www.cnblogs.com/weiming4219/p/7879443.html ...

  8. 使用Python多渠道打包apk

    使用Python生成多渠道包 往apk包中追加到一个空文件到META-INF目录以标识渠道,Android中获取此文件即可获得App的下载渠道 首先在info文件夹新建一个qdb.txt的空文本文件 ...

  9. Java语言基础&lpar;方法与数组&rpar;&lowbar;DAY05

    1:函数(掌握)   (1)定义在类中,有特定功能的一段小程序,可以独立运行.    (2)函数的格式:       修饰符 返回值类型 函数名(形参类型 形式参数1,形参类型 形式参数2...)   ...

  10. 从普通函数到对象方法 ------Windows窗口过程的面向对象封装

    原文地址:http://blog.csdn.net/linzhengqun/article/details/1451088 从普通函数到对象方法 ------Windows窗口过程的面向对象封装 开始 ...