根据URL发起HTTP请求,我的HTTPHelper。
完整的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。的更多相关文章
- [Java] 两种发起POST请求方法,并接收返回的响应内容的处理方式
1.利用apache提供的commons-httpclient-3.0.jar包 代码如下: /** * 利用HttpClient发起POST请求,并接收返回的响应内容 * * @param url ...
- java中两种发起POST请求,并接收返回的响应内容的方式 (转)
http://xyz168000.blog.163.com/blog/static/21032308201162293625569/ 2.利用java自带的java.net.*包下提供的工具类 代码如 ...
- python 爬虫 urllib模块 发起post请求
urllib模块发起的POST请求 案例:爬取百度翻译的翻译结果 1.通过浏览器捉包工具,找到POST请求的url 针对ajax页面请求的所对应url获取,需要用到浏览器的捉包工具.查看百度翻译针对某 ...
- 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有相关 ...
- 设计一个方法injectBeforeAsyncSend,能够实现如下功能:在发起异步请求之前打印出请求的类型、URL、method、body、timestamp 等信息。
异步请求逻辑注入 工作中我们需要对异步请求的请求信息打印日志,但是又不能耦合在业务代码中打印.请设计一个方法injectBeforeAsyncSend,能够实现如下功能:在发起异步请求之前打印出请求的 ...
- Ajax_02之XHR发起异步请求
1.Ajax: AJAX:Asynchronous Javascript And Xml,异步的JS和XML: 同步请求:地址栏输入URL.链接跳转.表单提交-- 异步请求:使用Ajax发起,底层使用 ...
- 关于java发起http请求
我们到底能走多远系列(41) 扯淡: 好久没总结点东西了,技术上没什么总结,感觉做事空牢牢的.最近也比较疲惫. 分享些东西,造福全人类~ 主题: 1,java模拟发起一个http请求 使用HttpUR ...
- android4.0 HttpClient 以后不能在主线程发起网络请求
android4.0以后不能在主线程发起网络请求,该异步网络请求. new Thread(new Runnable() { @Override public void run() { // TODO ...
- php 使用curl发起https请求
今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...
随机推荐
- Python之访问set
dict的作用是建立一组 key 和一组 value 的映射关系,dict的key是不能重复的. 有的时候,我们只想要 dict 的 key,不关心 key 对应的 value,目的就是保证这个集合的 ...
- Java语法糖(一)
概述 语法糖(Syntactic Sugar):主要作用是提高编码效率,减少编码出错的机会. 解语法糖发生在Java源码被编译成Class字节码的过程中,还原回简单的基础语法结构. 语法糖之一:泛型( ...
- 嵌入式 Linux线程锁详解pthread_mutexattr_t【转】
转自:http://blog.sina.com.cn/s/blog_8795b0970101il6g.html 在Posix Thread中定义有一套专门用于线程同步的mutex函数. . 创建和销毁 ...
- CentOS下Samba使用
1. 软件 Samba需要以下三个基本软件包,相关依赖包未列出 samba: The Samba SMB server samba-client: Samba (SMB) client program ...
- FormatDateTime 当前时间减去几小时的做法
top_start_modified := FormatDateTime('yyyy-mm-dd hh:mm:ss',(Now - ((1/24)*3))); top_end_modified ...
- ELK之filebeat收集多类型日志
1.IP规划 10.0.0.33:filebeat+tomcat,filebeat收集系统日志.tomcat日志发送到logstash 10.0.0.32:logstash,将日志写入reids(in ...
- HTML DOM介绍
HTML DOM定义了一系列的对象,以及访问和处理HTML的方法.通过DOM可以浏览所有的HTML元素,不但可以修改或者删除元素的文本和属性,而且可以创建新的元素. 一.首先对一个元素进行操作前,要得 ...
- Spring事务管理——事务的传播行为
1.简介 当事务方法被另一个事务方法调用时,必须指定事务应该如何传播.例如:方法可能继续在现有事务中运行,也可能开启一个新事务,并在自己的事务中运行. 事务的传播行为可以由传播属性指定.Spring定 ...
- 鼠标悬浮弹出标题制作JQuery
今天给客户制作的网站里面加个效果,当鼠标在列表图片之外时,标题不显示,当鼠标悬浮在图片之上时,标题从底部弹出. 效果图如下: 鼠标悬浮前: 鼠标悬浮后: html代码如下: <ul class= ...
- 修改linux iptable规则
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT(允许80端口通过防火墙)-A INPUT -m state --sta ...