完整的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. asp.net 字符串替换、截取。

    有时候要在一段字符串里面把某些字符替换成其他字符,怎么办? 例如: string image=@"csks/news/user_top/qqqq/qqqq.jpg"; image ...

  2. BZOJ 4500: 矩阵

    4500: 矩阵 Time Limit: 1 Sec  Memory Limit: 256 MBSubmit: 326  Solved: 182[Submit][Status][Discuss] De ...

  3. Codeforces Round #449 Div. 2 A B C (暂时)

    A. Scarborough Fair 题意 对给定的长度为\(n\)的字符串进行\(m\)次操作,每次将一段区间内的某一个字符替换成另一个字符. 思路 直接模拟 Code #include < ...

  4. 2017-2018 ACM-ICPC, NEERC, Southern Subregional Contest A E F G H I K M

    // 深夜补水题,清早(雾)写水文 A. Automatic Door 题意 \(n(n\leq 1e9)\)个\(employee\)和\(m(m\leq 1e5)\)个\(client\)要进门, ...

  5. hdu 1595(最短路变形好题)

    find the longest of the shortest Time Limit: 1000/5000 MS (Java/Others)    Memory Limit: 32768/32768 ...

  6. LeetCode OJ-- Reverse Words in a String

    https://oj.leetcode.com/problems/reverse-words-in-a-string/ 给一个字符串 abc  dd  m,返回 m dd abc. 注意:输入中可能有 ...

  7. EventBus 3.0: 入门使用及其使用 完全解析

    前言 EventBus是greenrobot再Android平台发布的以订阅-发布模式为核心的开源库. EventBus翻译过来是事件总线意思.可以这样理解:一个个(event)发送到总线上, 然后E ...

  8. GROOVY入门

    refer to 精通Groovy(IBM)https://www.ibm.com/developerworks/cn/education/java/j-groovy/j-groovy.html re ...

  9. eclipse 国际化 $NON-NLS-1$ 含义

    一.$NON-NLS-1$ 含义 Eclipse 如果每行代码里有这个字符串:$NON-NLS-1$ 表示:这一行的第一个字符串是不需要国际化的.同理$NON-NLS-2$,$NON-NLS-3$.. ...

  10. 求用delphi编写的LRC校验位算法函数,急!!!

    求用delphi编写的LRC校验位算法函数,急!!! 某命令串为":010200000001FC" 其16进制为“3A 30 31 30 32 30 30 30 30 30 30 ...