HttpHelper之我见
前几月一直用一个Http的访问类去调用WebApi,说句实话最开始没觉有什么,一是技术老,二是觉得比较简单,但是最近我一直关注云开发和AI这块儿微软技术,看到云平台调用API大多类似,所以回想这个早年的调用方式,感觉有老汤炖肉之感,实用又有价值,可以作为认识调用API的学习和使用,回味无穷。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web; namespace Bussiness.Helper
{
public class HttpHelper
{
/// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10; //http版本,默认是1.1,这里设置为1.0
}
else
{
request = WebRequest.Create(url) as HttpWebRequest; }
request.Method = "GET";
request.Headers.Add("Origin", "http://" + request.Host); //设置代理UserAgent和超时
//request.UserAgent = userAgent;
//request.Timeout = timeout;
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
} /// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
{
HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
//request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; //设置代理UserAgent和超时
//request.UserAgent = userAgent;
//request.Timeout = timeout; if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//发送POST数据
if (!(parameters == null || parameters.Count == ))
{
StringBuilder buffer = new StringBuilder();
int i = ;
foreach (string key in parameters.Keys)
{
if (i > )
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
i++;
}
}
//byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, , data.Length);
}
}
string[] values = request.Headers.GetValues("Content-Type");
return request.GetResponse() as HttpWebResponse;
} /// <summary>
/// 获取请求的数据
/// </summary>
public static string GetResponseString(HttpWebResponse webresponse)
{
var result = string.Empty;
using (Stream s = webresponse.GetResponseStream())
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
result = reader.ReadToEnd();
}
return result;
} /// <summary>
/// 验证证书
/// </summary>
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
if (errors == SslPolicyErrors.None)
return true;
return false;
}
}
}
特备提示:
乱码现象,注意改这里:
//byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
调用方式:
Dictionary<String, String> pList = new Dictionary<String, String>();
pList.Add("Location", userLog.Location);
pList.Add("Name", userLog.Name); ResultModel resultModel = new ResultModel();
var apiDomain = ConfigurationManager.AppSettings["ApiDomain"];
var url = @"" + apiDomain + "/api/AD/DeleteOneUser";
// var url = @"" + apiDomain + "/api/AD/GetEmail";
try
{
var response = HttpHelper.CreatePostHttpResponse(url, pList, , string.Empty, null);
var info = HttpHelper.GetResponseString(response).Replace("\\", "");
//info = info.Substring(1, info.Length - 2);
//string intoStr = "{" + info + "}"; resultModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultModel>(info); } catch(){}
HttpHelper之我见的更多相关文章
- HttpHelper
/// <summary> /// 类说明:HttpHelper类,用来实现Http访问,Post或者Get方式的,直接访问,带Cookie的,带证书的等方式,可以设置代理 /// 重要提 ...
- 抓取百万知乎用户信息之HttpHelper的迭代之路
什么是Httphelper? httpelpers是一个封装好拿来获取网络上资源的工具类.因为是用http协议,故取名httphelper. httphelper出现的背景 使用WebClient可以 ...
- Lind.DDD.Utils.HttpHelper里静态对象引出的Http超时问题
回到目录 Lind.DDD.Utils.HttpHelper组件主要实现了对HTTP的各种操作,如Get,Post,Put和Delete,它属于最纯粹的操作,大叔把它封装的目的主要为了实现与API安全 ...
- Sokcet方式请求HTTP/HTTPS的封装类HttpHelper
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; ...
- NODE.JS之我见
NODE.JS之我见 先说说为什么有这篇文章,关注NODE.JS 也有一段时间了,不敢说大彻大悟,但是对于NODE.JS能干什么,还是有一定的了解,笔者多年以前就研究过JavaScript引擎V8,可 ...
- HttpHelper类
using System;using System.Collections.Generic;using System.Text;using System.Net;using System.IO;usi ...
- HttpHelper类登录淘宝联盟并下载淘宝客订单xls
本次开发环境与工具如下:IE9.0浏览器 + IE抓包插件HttpWatch +WIN7 64位系统 + VS2005 IDE + .NET 2.0框架本想上传HttpWatch抓包插件,但由于文件超 ...
- C# HttpHelper 采集
httphelper http://www.sufeinet.com/thread-6-1-1.html
- [C#HttpHelper]类1.4正式版教程与升级报告
[C#HttpHelper]类1.4正式版教程与升级报告 导读 1.升级报告 2.HttpHelper1.4正式版下载 3.HttpHelper类使用方法, 4.最简单的Post与Get的写法 ...
随机推荐
- python_正则表达式学习
re.match()函数: 函数语法: re.mathch ( pattern , string , flags = 0) 参数说明: pattem 匹配的正则表达式 string 要匹配的字符串 f ...
- ABP进阶教程4 - 分页排序
点这里进入ABP进阶教程目录 下载插件 打开Datatables官网(https://datatables.net/download/) 下载插件,复制到JD.CRS.Web.Mvc\wwwroot\ ...
- Java并发编程艺术读书笔记
1.多线程在CPU切换过程中,由于需要保存线程之前状态和加载新线程状态,成为上下文切换,上下文切换会造成消耗系统内存.所以,可合理控制线程数量. 如何控制: (1)使用ps -ef|grep appn ...
- Wireshark抓包笔录--之指定IP地址筛选捕获结果
Wireshark安装 1.去官网下载相应的安装包 地址如下:https://www.wireshark.org/ 2.安装步骤,一路next,需要同意的地方点同意 3.安装完成后打开软件,如下: W ...
- CMD控制台如何把XXX.sql导入到数据库
mysql -u root -proot <"F:\Git\cyb.sql" 注意:mysql -u 用户名 -p没有空格加上密码 <"sql文件的路径&qu ...
- golang数据结构和算法之LinkedList链表
差不多自己看懂了,可以自己写测试了.:) LinkedList.go package LinkedList //"fmt" type Node struct { data int ...
- JDK、JVM、JRE关系
开始第一个Java程序 *保证计算机当中已经安装了文本编辑器EditPlus *安装JDK[JDK一般需要从oracle的官网下载],我们这里先用的JDK7 *在安装JDK的时候有jre JDK开发需 ...
- Selenium库详解
Selenium 自动化测试工具,支持多种浏览器 爬虫中解决JS渲染问题
- LG4341/BZOJ2251 「BJWC2010」外星联络 Trie
问题描述 LG4341 BZOJ2251 BZOJ需要权限号 题解 字符串的性质:一个字符串\(s\)所有的字串,等于\(s\)所有后缀的前缀. 枚举这个字符串的每一个后缀,将其插入一个\(\math ...
- Redis Pipelining
Redis是一种基于客户端-服务端模型以及请求/响应协议的TCP服务.这意味着通常情况下一个请求会遵循以下步骤: 客户端向服务端发送一个查询请求,并监听Socket返回,通常是以阻塞模式,等待服务端响 ...