完整的demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Web;
using System.IO.Compression;
using System.Collections.Specialized; namespace Application.Study
{
public class HttpHelper
{ /// <summary>
/// 发起http请求(POST)
/// </summary>
/// <param name="Url"></param>
/// <param name="Data"></param>
/// <returns></returns>
public static string SendPost(string Url, string Data)
{
return Send(Url, "POST", Data);
}
/// <summary>
/// 发起http请求(GET)
/// </summary>
/// <param name="Url"></param>
/// <returns></returns>
public static string SendGet(string Url)
{
return Send(Url, "GET");
}
/// <summary>
/// 发起请求
/// </summary>
/// <param name="url">目标地址</param>
/// <param name="method">发起方式:GET/POST</param>
/// <param name="data">发起时:附带数据</param>
/// <param name="config">配置信息为空则默认配置</param>
/// <returns>返回string</returns>
public static string Send(string Url, string Method, string Data = null, HttpConfig Config = null)
{
if (Config == null)
{
Config = new HttpConfig();
}
string result;
using (HttpWebResponse response = GetResponse(Url, Method, Data, Config))
{
Stream stream = response.GetResponseStream(); if (!String.IsNullOrEmpty(response.ContentEncoding))
{
if (response.ContentEncoding.Contains("gzip"))
{
stream = new GZipStream(stream, CompressionMode.Decompress);
}
else if (response.ContentEncoding.Contains("deflate"))
{
stream = new DeflateStream(stream, CompressionMode.Decompress);
}
} byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
int count;
byte[] buffer = new byte[];
while ((count = stream.Read(buffer, , buffer.Length)) > )
{
ms.Write(buffer, , count);
}
bytes = ms.ToArray();
} #region 检测流编码
Encoding encoding; //检测响应头是否返回了编码类型,若返回了编码类型则使用返回的编码
//注:有时响应头没有编码类型,CharacterSet经常设置为ISO-8859-1
if (!string.IsNullOrEmpty(response.CharacterSet) && response.CharacterSet.ToUpper() != "ISO-8859-1")
{
encoding = Encoding.GetEncoding(response.CharacterSet == "utf8" ? "utf-8" : response.CharacterSet);
}
else
{
//若没有在响应头找到编码,则去html找meta头的charset
result = Encoding.Default.GetString(bytes);
//在返回的html里使用正则匹配页面编码
Match match = Regex.Match(result, @"<meta.*charset=""?([\w-]+)""?.*>", RegexOptions.IgnoreCase);
if (match.Success)
{
encoding = Encoding.GetEncoding(match.Groups[].Value);
}
else
{
//若html里面也找不到编码,默认使用utf-8
encoding = Encoding.GetEncoding(Config.CharacterSet);
}
}
#endregion result = encoding.GetString(bytes);
}
return result;
} /// <summary>
/// 获取目标网址的返回数据
/// </summary>
/// <param name="Url"></param>
/// <param name="Method"></param>
/// <param name="Data"></param>
/// <param name="Config"></param>
/// <returns></returns>
private static HttpWebResponse GetResponse(string Url, string Method, string Data, HttpConfig Config)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = Method;
request.Referer = Config.Referer;
//有些页面不设置用户代理信息则会抓取不到内容
request.UserAgent = Config.UserAgent;
request.Timeout = Config.Timeout;
request.Accept = Config.Accept;
request.Headers.Set("Accept-Encoding", Config.AcceptEncoding);
request.ContentType = Config.ContentType;
request.KeepAlive = Config.KeepAlive; if (Url.ToLower().StartsWith("https"))
{
//这里加入解决生产环境访问https的问题--Could not establish trust relationship for the SSL/TLS secure channel
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidate);
} if (Method.ToUpper() == "POST")
{
if (!string.IsNullOrEmpty(Data))
{
byte[] DateBytes = Encoding.UTF8.GetBytes(Data); if (Config.GZipCompress)
{
using (MemoryStream MRStream = new MemoryStream())
{
using (GZipStream gZipStream = new GZipStream(MRStream, CompressionMode.Compress))
{
gZipStream.Write(DateBytes, , DateBytes.Length);
}
DateBytes = MRStream.ToArray();
}
} request.ContentLength = DateBytes.Length;
request.GetRequestStream().Write(DateBytes, , DateBytes.Length);
}
else
{
request.ContentLength = ;
}
} return (HttpWebResponse)request.GetResponse();
} /// <summary>
/// 解决https 生产环境无法为SSL/TLS安全信道建立信任关系
/// </summary>
/// <param name="sender"></param>
/// <param name="certificate"></param>
/// <param name="chain"></param>
/// <param name="errors"></param>
/// <returns></returns>
private static bool RemoteCertificateValidate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
//用户https请求
return true; //总是接受
}
}
/// <summary>
/// http配置信息
/// </summary>
public class HttpConfig
{
/// <summary>
/// Referer http 表头值设置或获取
/// </summary>
public string Referer { get; set; } /// <summary>
/// 默认(text/html)
/// </summary>
public string ContentType { get; set; } /// <summary>
/// 配置值:Accept HTTP 标头的值。
/// </summary>
public string Accept { get; set; } /// <summary>
/// 指定构成 HTTP 标头的名称/值对的集合。
/// </summary>
public string AcceptEncoding { get; set; } /// <summary>
/// 超时时间(毫秒)默认60000
/// </summary>
public int Timeout { get; set; } /// <summary>
/// User-Agent http表头值设置或获取
/// </summary>
public string UserAgent { get; set; } /// <summary>
/// POST请求时,数据是否进行gzip压缩
/// </summary>
public bool GZipCompress { get; set; } /// <summary>
/// 持久连接
/// </summary>
public bool KeepAlive { get; set; } public string CharacterSet { get; set; } public HttpConfig()
{
this.Timeout = ;
this.ContentType = "text/html; charset=" + Encoding.UTF8.WebName;
this.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36";
this.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
this.AcceptEncoding = "gzip,deflate";
this.GZipCompress = false;
this.KeepAlive = true;
this.CharacterSet = "UTF-8";
}
}
}

根据URL发起HTTP请求,我的HTTPHelper。的更多相关文章

  1. [Java] 两种发起POST请求方法,并接收返回的响应内容的处理方式

    1.利用apache提供的commons-httpclient-3.0.jar包 代码如下: /** * 利用HttpClient发起POST请求,并接收返回的响应内容 * * @param url ...

  2. java中两种发起POST请求,并接收返回的响应内容的方式  (转)

    http://xyz168000.blog.163.com/blog/static/21032308201162293625569/ 2.利用java自带的java.net.*包下提供的工具类 代码如 ...

  3. python 爬虫 urllib模块 发起post请求

    urllib模块发起的POST请求 案例:爬取百度翻译的翻译结果 1.通过浏览器捉包工具,找到POST请求的url 针对ajax页面请求的所对应url获取,需要用到浏览器的捉包工具.查看百度翻译针对某 ...

  4. NET MVC全局异常处理(一) 【转载】网站遭遇DDoS攻击怎么办 使用 HttpRequester 更方便的发起 HTTP 请求 C#文件流。 Url的Base64编码以及解码 C#计算字符串长度,汉字算两个字符 2019周笔记(2.18-2.23) Mysql语句中当前时间不能直接使用C#中的Date.Now传输 Mysql中Count函数的正确使用

    NET MVC全局异常处理(一)   目录 .NET MVC全局异常处理 IIS配置 静态错误页配置 .NET错误页配置 程序设置 全局异常配置 .NET MVC全局异常处理 一直知道有.NET有相关 ...

  5. 设计一个方法injectBeforeAsyncSend,能够实现如下功能:在发起异步请求之前打印出请求的类型、URL、method、body、timestamp 等信息。

    异步请求逻辑注入 工作中我们需要对异步请求的请求信息打印日志,但是又不能耦合在业务代码中打印.请设计一个方法injectBeforeAsyncSend,能够实现如下功能:在发起异步请求之前打印出请求的 ...

  6. Ajax_02之XHR发起异步请求

    1.Ajax: AJAX:Asynchronous Javascript And Xml,异步的JS和XML: 同步请求:地址栏输入URL.链接跳转.表单提交-- 异步请求:使用Ajax发起,底层使用 ...

  7. 关于java发起http请求

    我们到底能走多远系列(41) 扯淡: 好久没总结点东西了,技术上没什么总结,感觉做事空牢牢的.最近也比较疲惫. 分享些东西,造福全人类~ 主题: 1,java模拟发起一个http请求 使用HttpUR ...

  8. android4.0 HttpClient 以后不能在主线程发起网络请求

    android4.0以后不能在主线程发起网络请求,该异步网络请求. new Thread(new Runnable() { @Override public void run() { // TODO ...

  9. php 使用curl发起https请求

    今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...

随机推荐

  1. LOJ#2307. 「NOI2017」分身术

    $n \leq 100000$个点,$m \leq 100000$次询问,每次问删掉一些点后的凸包面积. 不会啦写个20暴力,其实是可以写到50的.当个计算几何板子练习. //#include< ...

  2. python字符串加密与反解密

    在生产中会遇到很多情况是需要加密字符串的(如访问或存储密码)这些需求造就了需要字符串加密,以及反解密的问题,推荐两种方法来实现,下附代码: #!/usr/bin/env python3 # -*- c ...

  3. C 语言调用python 脚本函数

    刚好几个月前做过,C++ 函数里面先加载python 脚本,再调用 里面的 def 函数,我把代码贴出来,你在main 函数里面,调用getDataByScript 函数,另外相同目录下放一个 fuc ...

  4. mysql事物中行锁与表锁

    事物与锁 什么叫不支持事物: 首先要了解数据库里的事务是什么意思.事务在计算机数据库里 :在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit).在关系数据库中,一个事务可以 ...

  5. JavaScript中的普通函数和箭头函数

    最近被问到了一个问题: javaScript 中的箭头函数 ( => ) 和普通函数 ( function ) 有什么区别? 我当时想的就是:这个问题很简单啊~(flag),然后做出了错误的回答 ...

  6. QQ分享到电脑SDK bug

    问题:当图文(图片+文字+url)混合分享到我的电脑时,就会出bug,只显示图片. 经过测试: params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL," ...

  7. HTML小技巧将table边框改为细线

    HTML制作新手在用TABLE表格时,会碰到如何改变边线粗线,因为默认的TABLE边线设置即使是1px 是很粗的.因此会使用其他一些方法来制作出细线边框,这里介绍一种利用CSS来实现细线的方法,很有效 ...

  8. linux中xargs用法

    参数代换: xargs xargs 是在做什么的呢?就以字面上的意义来看, x 是加减乘除的乘号,args 则是 arguments (参数) 的意思,所以说,这个玩意儿就是在产生某个命令的参数的意思 ...

  9. 手机APP脚本录制(LoadRunner 12)

    最近因项目需要,研究了下手机APP脚本录制方法,有需要的童鞋可参考使用! 方法1: 在手机网络中设置网络代理,使用LR12选择Mobile Application – HTTP/HTML协议中代理录制 ...

  10. HTML5 Canvas 绘制澳大利亚国旗

    代码: <!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type ...