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的写法 ...
随机推荐
- JDK8日常开发系列:Consumer详解
java.util.function中 Function, Supplier, Consumer, Predicate和其他函数式接口广泛用在支持lambda表达式的API中.这些接口有一个抽象方法, ...
- 记一次接口调试错误: {"timestamp":"2019-09-11T03:04:30.036+0000","status":500,"error":"Internal Server Error","message":"Could not write JSON: Object is null; nested exception is com.fasterxml.jackson
接口测试中用postman测试返回是正常的,但是使用其他人去调用就出错了,找了半天,才想起来使用了nginx,用于端口的代理转发.然后根据错误信息发现json格式的某个字段为null,结合日志中的报文 ...
- JavaScript—图片与base64编码互相转换
图片转换为base64编码 <input type = "file" id = "file" onchange="popFileName(thi ...
- openresty配置
目录 环境 wsl安装 openresty安装 openssl版本问题 Lua模块安装 openresty使用 nginx常用命令 nginx.conf 配置 lua 的一些坑 OpenResty缓存 ...
- CodeForces - 1250B The Feast and the Bus (贪心+暴力)
题意 https://vjudge.net/problem/CodeForces-1250B 每个人属于队伍ai,汽车一次至多载两只队伍(全员),费用为车的容量*载人次数,问最少花费. 思路 k(队伍 ...
- hibernate之主键生成策略
1. hibernate的主键生成器: generator元素:表示了一个主键生成器,它用来为持久化类实例生成唯一的标识 . 连接数据库的xml hibernate.cfg.xml <?xml ...
- 1.Java基础_Java核心机制简介
Java的两种核心机制 Java虚拟机机制 Java垃圾回收机制 解释名词 J2SDK&JRE: J2SDK=JDK=Software Development Kit(软件开发包) JRE=J ...
- 3.Python爬虫入门_正则表达式(简单例子)
#2019-11-23 import requests import time import re #Python正则表达式库 if __name__=='__main__': #海量爬取图片数据 # ...
- G1 垃圾收集器架构和如何做到可预测的停顿(阿里)
CMS垃圾回收机制 参考:图解 CMS 垃圾回收机制原理,-阿里面试题 CMS与G1的区别 参考:CMS收集器和G1收集器优缺点 写这篇文章是基于阿里面试官的一个问题:众所周期,G1跟其他的垃圾回收算 ...
- sudo apt-get 与 yum 常用命令
yum -RedHat:CentOS... -xxx.rpmsudo apt-get -Debian:Ubuntu... -xxx.deb 安装工具rpm -ivh yum-2.0.4-1.rh ...