老是浪费时间写这个类,干脆记录在博客里:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks; namespace XiaoDao.Core
{
public class WebRequestHelper
{
private const string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"; #region HttpPost
public static string HttpPost(WebRequestOption options)
{
if (options.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
ServicePointManager.SecurityProtocol = options.SecurityProtocol;
}
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(options.Url);
myRequest.Method = "POST";
if (options.CC != null)
{
myRequest.CookieContainer = options.CC;
}
if (options.Headers.Count > 0)
{
foreach (var item in options.Headers)
{
myRequest.Headers.Add(item.Key, item.Value);
}
}
if (options.ContentType != null)
{
myRequest.ContentType = options.ContentType;
}
else
{
//myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentType = "application/json";
}
myRequest.UserAgent = userAgent; byte[] payload = null;
string formData = GetFormData(options.Paras);
if (!string.IsNullOrEmpty(formData))
{
payload = Encoding.UTF8.GetBytes(formData);
myRequest.ContentLength = payload.Length;
}
if (options.MyProxy != null)
{
myRequest.Proxy = options.MyProxy;
}
using (Stream mySream = myRequest.GetRequestStream())
{
if (payload != null && payload.Length > 0)
{
mySream.Write(payload, 0, payload.Length);
}
} try
{
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
using (StreamReader myReader = new StreamReader(myResponse.GetResponseStream(), options.MyEncoding))
{
string responseText = myReader.ReadToEnd();
return responseText;
}
}
}
catch (Exception ex)
{
options.MyException = ex;
return null;
}
} public static async Task<string> HttpPostAsync(WebRequestOption options)
{
if (options.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
ServicePointManager.SecurityProtocol = options.SecurityProtocol;
}
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(options.Url);
myRequest.Method = "POST";
if (options.CC != null)
{
myRequest.CookieContainer = options.CC;
}
if (options.Headers.Count > 0)
{
foreach (var item in options.Headers)
{
myRequest.Headers.Add(item.Key, item.Value);
}
}
if (options.ContentType != null)
{
myRequest.ContentType = options.ContentType;
}
else
{
myRequest.ContentType = "application/x-www-form-urlencoded";
//myRequest.ContentType = "application/json";
}
myRequest.UserAgent = userAgent; byte[] payload = null;
string formData = GetFormData(options.Paras);
if (!string.IsNullOrEmpty(formData))
{
payload = Encoding.UTF8.GetBytes(formData);
myRequest.ContentLength = payload.Length;
}
if (options.MyProxy != null)
{
myRequest.Proxy = options.MyProxy;
}
using (Stream mySream = myRequest.GetRequestStream())
{
if (payload != null && payload.Length > 0)
{
mySream.Write(payload, 0, payload.Length);
}
} try
{
using (HttpWebResponse myResponse = (HttpWebResponse)await myRequest.GetResponseAsync())
{
using (StreamReader myReader = new StreamReader(myResponse.GetResponseStream(), options.MyEncoding))
{
string responseText = myReader.ReadToEnd();
return responseText;
}
}
}
catch (Exception ex)
{
options.MyException = ex;
return null;
}
} public static async Task<string> HttpPostJsonAsync(WebRequestOption options)
{
if (options.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
ServicePointManager.SecurityProtocol = options.SecurityProtocol;
}
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(options.Url);
myRequest.Method = "POST";
if (options.CC != null)
{
myRequest.CookieContainer = options.CC;
}
if (options.Headers.Count > 0)
{
foreach (var item in options.Headers)
{
myRequest.Headers.Add(item.Key, item.Value);
}
}
myRequest.ContentType = "application/json";
myRequest.UserAgent = userAgent; byte[] payload = null;
string jsonData = options.Paras.ToString();
if (!string.IsNullOrEmpty(jsonData))
{
payload = Encoding.UTF8.GetBytes(jsonData);
myRequest.ContentLength = payload.Length;
}
if (options.MyProxy != null)
{
myRequest.Proxy = options.MyProxy;
}
using (Stream mySream = myRequest.GetRequestStream())
{
if (payload != null && payload.Length > 0)
{
mySream.Write(payload, 0, payload.Length);
}
} try
{
using (HttpWebResponse myResponse = (HttpWebResponse)await myRequest.GetResponseAsync())
{
using (StreamReader myReader = new StreamReader(myResponse.GetResponseStream(), options.MyEncoding))
{
string responseText = myReader.ReadToEnd();
return responseText;
}
}
}
catch(WebException ex)
{
var res = (HttpWebResponse)ex.Response;
using (StreamReader myReader = new StreamReader(res.GetResponseStream(), options.MyEncoding))
{
string responseText = myReader.ReadToEnd();
return responseText;
}
}
catch (Exception ex)
{
options.MyException = ex;
return null;
}
}
#endregion #region HttpGet
public static string HttpGet(WebRequestOption options)
{
string formData = GetFormData(options.Paras);
if (options.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
ServicePointManager.SecurityProtocol = options.SecurityProtocol;
}
string url = string.IsNullOrEmpty(formData) ? options.Url : options.Url + "?" + formData;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "GET";
if (options.Headers.Count > 0)
{
foreach (var item in options.Headers)
{
myRequest.Headers.Add(item.Key, item.Value);
}
}
if (options.CC != null)
{
myRequest.CookieContainer = options.CC;
}
myRequest.UserAgent = userAgent;
if (url.StartsWith("https://"))
{
//myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentType = "application/json";
}
myRequest.Accept = "*/*";
myRequest.KeepAlive = true;
if (options.MyProxy != null)
{
myRequest.Proxy = options.MyProxy;
}
try
{
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
using (Stream sResponse = myResponse.GetResponseStream())
{
using (StreamReader myReader = new StreamReader(sResponse, options.MyEncoding))
{
options.Status = myResponse.StatusCode;
string responseText = myReader.ReadToEnd();
return responseText;
}
}
}
}
catch (Exception ex)
{
options.MyException = ex;
return null;
}
} public static async Task<string> HttpGetAsync(WebRequestOption options)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); string formData = GetFormData(options.Paras);
if (options.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
ServicePointManager.SecurityProtocol = options.SecurityProtocol;
}
string url = string.IsNullOrEmpty(formData) ? options.Url : options.Url + "?" + formData;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "GET";
if (options.Headers.Count > 0)
{
foreach (var item in options.Headers)
{
myRequest.Headers.Add(item.Key, item.Value);
}
}
if (options.CC != null)
{
myRequest.CookieContainer = options.CC;
}
myRequest.UserAgent = userAgent;
if (url.StartsWith("https://"))
{
//myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentType = "application/json";
}
myRequest.Accept = "*/*";
myRequest.KeepAlive = true;
if (options.MyProxy != null)
{
myRequest.Proxy = options.MyProxy;
}
try
{
using (HttpWebResponse myResponse = (HttpWebResponse)await myRequest.GetResponseAsync())
{
using (Stream sResponse = myResponse.GetResponseStream())
{
using (StreamReader myReader = new StreamReader(sResponse, options.MyEncoding))
{
options.Status = myResponse.StatusCode;
string responseText = myReader.ReadToEnd();
return responseText;
}
}
}
}
catch (Exception ex)
{
options.MyException = ex;
return null;
}
}
#endregion public static async Task<string> ExecQueryAsync(string url)
{
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string resultStr = await response.Content.ReadAsStringAsync();
return resultStr;
}
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
} #region 帮助方法
public static string GetFormData(object paras)
{
StringBuilder formData = new StringBuilder();
if (paras != null)
{
Type t = paras.GetType();
if (t.Name.Contains("Dictionary"))
{
foreach (KeyValuePair<String, String> kvp in paras as Dictionary<string, string>)
{
if (formData.ToString() == "")
{
formData.Append(kvp.Key + "=" + kvp.Value);
}
else
{
formData.Append("&" + kvp.Key + "=" + kvp.Value);
}
}
}
else if (t.Name == "String")
{
formData.Append(paras.ToString());
}
else
{
foreach (PropertyInfo pi in t.GetProperties())
{
var jsonProperty = pi.CustomAttributes.SingleOrDefault(p => p.AttributeType.FullName == "Newtonsoft.Json.JsonPropertyAttribute");
string name = jsonProperty == null ? pi.Name : jsonProperty.ConstructorArguments[0].Value.ToString();
object val = pi.GetValue(paras, null); if (formData.ToString() == "")
{
formData.Append(name + "=" + val);
}
else
{
formData.Append("&" + name + "=" + val);
}
}
}
}
return formData.ToString();
}
#endregion
}
public class WebRequestOption
{
public string Url { get; set; }
/// <summary>
/// 可以是匿名对象, 可以是字典
/// </summary>
public object Paras { get; set; }
public Dictionary<string, string> Headers = new Dictionary<string, string>();
public CookieContainer CC { get; set; }
public Encoding MyEncoding { get; set; }
public WebProxy MyProxy { get; set; }
public HttpStatusCode Status { get; set; }
public Exception MyException { get; set; }
public SecurityProtocolType SecurityProtocol { get; set; }
public string ContentType { get; set; } /// <summary>
/// 没有任何关于SecurityProtocold的默认设置
/// </summary>
public WebRequestOption()
{
if (this.MyEncoding == null)
{
this.MyEncoding = Encoding.UTF8;
}
}
/// <summary>
/// htts协议将默认设置为Tls1.0
/// </summary>
/// <param name="url"></param>
/// <param name="paras"></param>
public WebRequestOption(string url, object paras = null)
{
this.Url = url;
if (paras != null)
{
this.Paras = paras;
}
if (this.MyEncoding == null)
{
this.MyEncoding = Encoding.UTF8;
}
if (this.Url.StartsWith("https") && this.SecurityProtocol == SecurityProtocolType.SystemDefault)
{
this.SecurityProtocol = SecurityProtocolType.Tls12;
}
}
}
}

  

哈哈,这下爽了

WebRequestHelper的更多相关文章

  1. 请求WebApi的几种方式

    目前所了解的请求WebAPI的方式有通过后台访问api 和通过js 直接访问api接口 首先介绍下通过后台访问api的方法,可以使用HttpClient的方式也可以使用WebRequest的方式 1. ...

  2. C# v3微信 access token 过期处理的问题

    //记录access token 申请时的时间 private static DateTime GetAccessToken_Time; /// <summary> /// 过期时间为72 ...

  3. Magicodes.WeiChat——版本发布历史

    购买地址:https://item.taobao.com/item.htm?id=520205558575 您可以在新标签页打开此图,以查看原始图片. Magicodes.WeiChat为湖南心莱信息 ...

  4. c#后台调用API

    前两周赶上项目第一个版本上线,着实忙了一把,毕竟只有两个人负责.如今已完结,总算喘了一口气,现在任务就是写API.测API,许久之前写过JS前台调用 项目API,也写过后台调用开放的手机号归属地查询, ...

  5. C#使用Http的Post方式请求webservice

    webservice是以前比较流行的跨系统.跨语言.跨平台的数据交互技术.最近工作中调用Java作为服务端开放的webser,我是通过VS205生成webservice工具类的方式进行接口调用的.用这 ...

  6. WebApi的调用-2.后台调用

    httpClient调用方式 namespace SOA.Common { //httpClient调用WebApi public class HttpClientHelper { public st ...

  7. C#获取用户基本信息一(关注了公众号的用户)

    一.获取Code  假设我们需要网页授权的页面的地址为redirect_uri 需要获取Code的话我们第一步是跳转到授权地址,我们第一步便是获取拼接授权地址 --采用snsapi_base方式 pu ...

  8. C#获取网页信息核心方法(入门一)

    目录:信息采集入门系列目录 下面记录的是我自己整理的C#请求页面核心类,主要有如下几个方法 1.HttpWebRequest Get请求获得页面html 2.HttpWebRequest Post请求 ...

  9. 亲手搭建一个基于Asp.Net WebApi的项目基础框架2

    本篇目的:封装一些抽象类 1::封装日志相关类 2:封装一个Service操作类 3:封装缓存操作类 4:封装其他一些常用Helper 1.1在Framework项目里面建立好相关操作类文件夹,以便于 ...

随机推荐

  1. Android的ProgressBar进度条-android学习之旅(三十一)

    ProgressBar 简介 ProgressBar是一种很常用的Ui,用于给复杂的操作显示进度,提供更好的用户相应.使用setProgress()incrementProgressBy()来设置进度 ...

  2. [Error]Can't install RMagick 2.13.4. You must have ImageMagick 6.4.9 or later.

    gem 安装ruby插件的时候 出现了一个错误 Installing rmagick 2.13.4 with native extensions Gem::Installer::ExtensionBu ...

  3. 1020. Tree Traversals (25) -BFS

    题目如下: Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder ...

  4. DB 查询分析器 6.04 在 Windows 10 上的安装与运行展示

    DB查询分析器 6.04 在 Windows 10 上的安装与运行展示 中国本土程序员马根峰(CSDN专访马根峰:海量数据处理与分析大师的中国本土程序员 http://www.csdn.net/art ...

  5. 【一天一道LeetCode】#94. Binary Tree Inorder Traversal

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  6. int(*p)[]和int(**p)[]

    1. int(*p)[10]: 根据运算符的结合律,()的优先级最高,所以p是一个指针,指向的一个维度为10的一维数组. p一个指向数组的某一行 int a[1][4]={1,2,3,4}; int ...

  7. 海量数据挖掘MMDS week4: 推荐系统Recommendation System

    http://blog.csdn.net/pipisorry/article/details/49205589 海量数据挖掘Mining Massive Datasets(MMDs) -Jure Le ...

  8. JAVA之旅(十三)——线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this

    JAVA之旅(十三)--线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this 我们继续上个篇幅接着讲线程的知识点 一.线程的安全性 当我们开启四个窗口(线程 ...

  9. Adapterview和adapter的联系

    在J2EE中提供过一种非常好的框架--MVC框架,实现原理:数据模型M(Model)存放数据,利用控制器C(Controller)将数据显示在视图V(View)上.在Android中有这样一种高级控件 ...

  10. Ajax核心--XMLHttpRequest对象

    XMLHttpRequest 对象是AJAX功能的核心,学习XMLHttpRequest对象就先从创建XMLHttpRequest 对象开始,了解在不同的浏览器中创建XMLHttpRequest 对象 ...