【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种:
1.处理http POST请求【XML格式、无解压】;
2.处理http GET请求【XML格式、无解压】;
3.处理http POST请求【可以解压】;
4.处理http GET请求【可以解压】。
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks; namespace Common
{
public class HttpService
{
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
//直接确认,否则打不开
return true;
} #region 1.处理http POST请求【XML格式、无解压】
/// <summary>
/// 处理http POST请求【XML格式、无解压】
/// </summary>
/// <param name="xml">请求参数</param>
/// <param name="url">请求接口地址</param>
/// <param name="timeout">设置超时时间</param>
/// <returns>http POST成功后返回的数据,失败抛WebException异常</returns>
public static string PostXMLRequest(string xml, string url, int timeout = )
{
System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接 string result = "";//返回结果 HttpWebRequest request = null;
HttpWebResponse response = null;
Stream reqStream = null; try
{
//设置最大连接数
ServicePointManager.DefaultConnectionLimit = ;
//设置https验证方式
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
} /***************************************************************
* 下面设置HttpWebRequest的相关属性
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST";
request.Timeout = timeout * ; //设置POST的数据类型和长度
request.ContentType = "text/xml";
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
request.ContentLength = data.Length; //往服务器写入数据
reqStream = request.GetRequestStream();
reqStream.Write(data, , data.Length);
reqStream.Close(); //获取服务端返回
response = (HttpWebResponse)request.GetResponse(); //获取服务端返回数据
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd().Trim();
sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{
System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{ }
catch (Exception e)
{ }
finally
{
//关闭连接和流
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return result;
}
#endregion #region 2.处理http GET请求【XML格式、无解压】
/// <summary>
/// 处理http GET请求【XML格式、无解压】
/// </summary>
/// <param name="url">请求的url地址</param>
/// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
public static string GetXMLRequest(string url)
{
System.GC.Collect();
string result = ""; HttpWebRequest request = null;
HttpWebResponse response = null; //请求url以获取数据
try
{
//设置最大连接数
ServicePointManager.DefaultConnectionLimit = ;
//设置https验证方式
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
} /***************************************************************
* 下面设置HttpWebRequest的相关属性
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //获取服务器返回
response = (HttpWebResponse)request.GetResponse(); //获取HTTP返回数据
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd().Trim();
sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{ System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{ } finally
{
//关闭连接和流
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return result;
}
#endregion #region 3.处理http POST请求【可以解压】
/// <summary>
/// 处理http POST请求【可以解压】
/// </summary>
/// <param name="param">请求参数</param>
/// <param name="url">请求接口地址</param>
/// <param name="timeout">设置超时时间</param>
/// <returns>http POST成功后返回的数据,失败抛WebException异常</returns>
public static string Post(string param, string url, int timeout = )
{
System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接 string result = "";//返回结果 HttpWebRequest request = null;
HttpWebResponse response = null;
Stream reqStream = null;
StreamReader sr = null;
try
{
//设置最大连接数
ServicePointManager.DefaultConnectionLimit = ; /***************************************************************
* 下面设置HttpWebRequest的相关属性
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST";
request.Timeout = timeout * ; //设置POST的数据类型
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; byte[] data = System.Text.Encoding.UTF8.GetBytes(param); request.UserAgent = "Mozilla/4.0";
request.Headers.Add("Accept-Encoding", "gzip, deflate"); //设置POST的数据长度
request.ContentLength = data.Length; //往服务器写入数据
reqStream = request.GetRequestStream();
reqStream.Write(data, , data.Length);
reqStream.Close(); //获取服务端返回
response = (HttpWebResponse)request.GetResponse(); //获取服务端返回数据
if (response.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
{
using (Stream streamReceive = response.GetResponseStream())
{
using (var zipStream = new GZipStream(streamReceive, CompressionMode.Decompress))
{
using (sr = new StreamReader(zipStream, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
}
}
else
{
using (Stream streamReceive = response.GetResponseStream())
{
using (sr = new StreamReader(streamReceive, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
} sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{ System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{ }
catch (Exception e)
{ }
finally
{
//关闭连接和流
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return result;
}
#endregion #region 4.处理http GET请求【可以解压】
/// <summary>
/// 处理http GET请求【可以解压】
/// </summary>
/// <param name="url">请求的url地址</param>
/// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
public static string Get(string url)
{
System.GC.Collect();
string result = ""; HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader sr = null; //请求url以获取数据
try
{
//设置最大连接数
ServicePointManager.DefaultConnectionLimit = ; /***************************************************************
* 下面设置HttpWebRequest的相关属性
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //获取服务器返回
response = (HttpWebResponse)request.GetResponse(); //获取HTTP返回数据
//获取服务端返回数据
if (response.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
{
using (Stream streamReceive = response.GetResponseStream())
{
using (var zipStream =
new GZipStream(streamReceive, CompressionMode.Decompress))
{
using (sr = new StreamReader(zipStream, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
}
}
else
{
using (Stream streamReceive = response.GetResponseStream())
{
using (sr = new StreamReader(streamReceive, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
}
sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{ System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{ if (e.Status == WebExceptionStatus.ProtocolError)
{ } }
catch (Exception e)
{ }
finally
{
//关闭连接和流
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return result;
}
#endregion
}
}
【原创】标准HTTP请求工具类的更多相关文章
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
随机推荐
- IDEA 使用技巧 Update
IDEA使用起来和Eclipse很大区别. 1.快捷键. 因为一个个熟悉起来费时间,就直接在Preferences—keymap里选择了Eclipse OS X,这样快捷键就转换到了Mac下Eclip ...
- [AHOI2009]最小割
题目 最小割的可行边和必须边 可行边\((u,v)\)需要满足以下两个条件 满流 残量网络中不存在\(u\)到\(v\)的路径 这个挺好理解的呀,如果存在还存在路径的话那么这条边就不会是瓶颈了 必须边 ...
- [SHOI2012]回家的路
题目背景 SHOI2012 D2T1 题目描述 2046 年 OI 城的城市轨道交通建设终于全部竣工,由于前期规划周密,建成后的轨道交通网络由2n2n条地铁线路构成,组成了一个nn纵nn横的交通网.如 ...
- tbb静态库编译
源自Intel论坛 Jeff的方法https://software.intel.com/en-us/forums/intel-threading-building-blocks/topic/29779 ...
- ceph 分布式存储安装
[root@localhost ~]# rm -rf /etc/yum.repos.d/*.repo 下载阿里云的base源 [root@localhost ~]# wget -O /etc/yum. ...
- 常用的sql语法_Row_Number
可用来分页,也可以用来egg:获取同类型的最新的信息 ROW_NUMBER() 说明:返回结果集分区内行的序列号,每个分区的第一行从1开始.语法:ROW_NUMBER () OVER ([ < ...
- 【转】ios开发证书,描述文件,bundle ID的关系
ios开发证书,描述文件,bundle ID的关系 苹果为了控制应用的开发与发布流程,制定了一套非常复杂的机制.这里面的关键词有:个人开发者账号,企业开发者账号,bundle ID,开发证书,发布 ...
- BI之报表测试总结
报表测试总结: 1.测试准备工作: 数据准备 保证足够多的有效数据 清楚报表中涉及到的算法.公式 清楚业务功能接口 2.报表测试点 基本测试点:界面.控件.格式.布局.明显的数据错误.js报错.报表标 ...
- zabbix 监控机器监听的端口 + 触发器 表达式理解
在zabbix web 页面配置item,监控监听的21端口 配置trigger 参考:http://www.cnblogs.com/saneri/p/6126786.html 5. {www.zab ...
- 渲染引擎,HTML解析
这是how browser to work 的翻译 转自:携程设计委员会 渲染引擎 渲染引擎的职责是……渲染,也就是把请求的内容显示到浏览器屏幕上. 默认情况下渲染引擎可以显示HTML,XML文档以及 ...