以下是个人在项目开发过程中,总结的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请求工具类的更多相关文章

  1. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  2. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  5. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  6. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  7. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  8. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

  9. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

随机推荐

  1. c++程序员学习go

    作为一个c++程序员学习go编程的笔记.首先声明本人文笔太差,当你阅读一点觉得实在无法阅读下去时请移步. 下载安装go,安装完毕后会增加系统环境变量path内容指定go程序所在目录,可以打开cmd输入 ...

  2. 常用的npm命令

    npm ls -g 列出全局安装的所有模块 npm ls webpack -g 查看全局安装的模块版本信息 npm view webpack versions 查看npm服务器上的全部版本信息 npm ...

  3. Python中乘法

    1.numpy乘法运算中"*"或multiply(),是数组元素逐个计算,具体代码如下: import numpy as np # 2-D array: 2 x 3 two_dim ...

  4. RANSAC与 最小二乘(LS, Least Squares)拟合直线的效果比较

    代码下载地址: 1.Matlab版本:http://pan.baidu.com/s/1eQIzj3c.进入目录后,请自行定位到该博客的源代码与数据的目录“

  5. 一条SQL语句执行得很慢原因有哪些

    一条SQL语句执行得很慢,要分两种情况: 1.大多数情况是正常,偶尔很慢 数据库在处理数据忙时候,更新或新增数据都会暂时记录到redo log日志,等空闲时把数据同步到磁盘.假设数据库一直很忙,更新又 ...

  6. ps命令使用详解

    转自:http://blog.csdn.net/lsbhjshyn/article/details/18549869 ps:要对进程进行监测和控制,首先必须要了解当前进程的情况,也就是需要查看当前进程 ...

  7. 清除浮动元素的margin-top失效原因(更改之前的错误)

    //样式代码body,div{ margin:; padding:; } .box1{ background:#900; width:200px; height:200px; margin:20px ...

  8. [原创]升级Gerrit的commit-msg,检查git commit时必须填写开发任务编号TaskID

    公司使用git+gerrit+jenkins进行持续集成实践,其中gerrit用来进行Code Review.另外我们自己研发了一套敏捷项目管理系统TPM(TeamPlus Management),用 ...

  9. 解决vue跨域axios异步通信

    在项目中,常常需要从后端获取数据内容.特别是在前后端分离的时候,前端进行了工程化部署,跨域请求成了一个前端必备的技能点.好在解决方案很多. 在vue中,在开发中,当前使用较多的是axios进行跨域请求 ...

  10. 关于mysql-mybatis批量添加

    mybatis怎么实现一次插入多条数据   以后从新浪博客转到博客园这边来记录把.   这篇地址:http://blog.sina.com.cn/s/blog_13e9702640102ysho.ht ...