1. helper 类封装
  2. 调用

1. 引用的库类

\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\System.dll
System.Net.HttpWebRequest

2代码 helper 类封装

/// <summary>
/// REST帮助类
/// </summary>
public class RESTHelper
{
/// <summary>
/// 不含请求参数的URL
/// </summary>
public string EndPoint { get; set; } /// <summary>
/// 请求动作
/// </summary>
public HttpVerb Method { get; set; } /// <summary>
/// 请求格式(application/json,text/xml,application/x-www-form-urlencoded,multipart/form-data)
/// </summary>
public string ContentType { get; set; } /// <summary>
/// 构造函数
/// </summary>
/// <param name="endpoint">路径</param>
/// <param name="method">请求动作</param>
public RESTHelper(string endpoint, HttpVerb method)
{
EndPoint = endpoint;
Method = method;
ContentType = "application/json";
} /// <summary>
/// 将对象转换为json格式然后命令,一般是使用post请求
/// </summary>
/// <param name="jsonmodel">参数对象,不能传入string类型</param>
/// <param name="encode">字符编码,可为null</param>
/// <returns></returns>
public string MakeJsonPostRequest(object jsonmodel, Encoding encode = null, WebHeaderCollection headerCollection = null)
{
string postData = "";
if (jsonmodel != null)
{
//将对象序列化为json字符串,忽略null值
postData = JsonConvert.SerializeObject(jsonmodel, new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" });
}
return MakeRequest("", postData, encode, headerCollection);
} /// <summary>
/// 发送请求,包含url的参数和请求数据
/// </summary>
/// <param name="parameters">请求参数,如page=1&page_size=20</param>
/// <param name="postData">请求数据</param>
/// <param name="encode">字符编码,可为null</param>
/// <returns></returns>
public string MakeRequest(string parameters, string postData, Encoding encode = null, WebHeaderCollection headerCollection = null)
{
// endpoint与请求参数拼接成完整的请求url
string requesturlstring = EndPoint + (string.IsNullOrEmpty(parameters) ? "" : "?" + parameters);
// 请求前记录日志
DateTime dt = DateTime.Now;
if (WriteLog.LoggerInstance.IsDebugEnabled) WriteLog.WriteLogger.Debug("[REST请求] 请求时间:" + dt.ToString("mm:ss.fff") + "\r\nURI:" + requesturlstring + "\r\n发送请求:" + postData);
// 初始化http请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requesturlstring);
if (headerCollection != null)
request.Headers = headerCollection;
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
request.Timeout = ConfigInfo.RESTTimeOut; //request.Credentials = new NetworkCredential("username", "password");//传入验证信息 // 编码格式
encode = encode == null ? Encoding.UTF8 : encode;
// POST时,向流写入postData数据
if (!string.IsNullOrEmpty(postData) && Method == HttpVerb.POST)
{
var bytes = encode.GetBytes(postData);
// 设置请求数据的长度
request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
} // 返回值
var responseValue = string.Empty; // 获取返回值
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream, encode))
{
responseValue = reader.ReadToEnd();
// 记录返回结果日志
if (WriteLog.LoggerInstance.IsDebugEnabled) WriteLog.WriteLogger.Debug("[REST结果] 请求时间:" + dt.ToString("mm:ss.fff") + "\r\nURI:" + requesturlstring + "\r\n返回数据:" + responseValue); return responseValue;
}
}
}
} /// <summary>
/// 将json字符串转换为对象(使用DataContractJsonSerializer)
/// </summary>
/// <param name="response"></param>
/// <param name="dateformatstring">时间格式</param>
/// <returns></returns>
public T ConvertJson<T>(string response)
{
try
{
DataContractJsonSerializer Serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(response)))
{
return (T)Serializer.ReadObject(stream);
}
}
catch (Exception ex)
{
WriteLog.WriteLogger.Error("将json字符串转换为对象出错!\r\njson为:" + response, ex);
return default(T);
}
} /// <summary>
/// 将json字符串转换为对象(使用Json.net)
/// </summary>
/// <param name="response"></param>
/// <param name="dateformatstring">时间格式</param>
/// <returns></returns>
public T JsonNetConvertJson<T>(string response)
{
try
{
JsonSerializerSettings jsSetting = new JsonSerializerSettings();
jsSetting.NullValueHandling = NullValueHandling.Ignore;
return JsonConvert.DeserializeObject<T>(response, jsSetting);
//return JsonConvert.DeserializeObject<T>(response);
}
catch (Exception ex)
{
Common.WriteLog.Error("将json字符串转换为对象出错!\r\njson为:" + response, ex);
return default(T);
}
}
} /// <summary>
/// http请求方法/动作
/// </summary>
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}

3. 调用

public class AClass{}
public AClass RequestAClass(string id)
{
AClass entity = null; try
{
var uri = ConfigInfo.GetRestUri("GetAClassInfo"); // 参数校验
if (string.IsNullOrEmpty(id))
return null; var restHelper = new RESTHelper(uri.Uri, HttpVerb.GET);
var jsonString = restHelper.MakeRequest(id);
entity = restHelper.ConvertJson<PrisonerInfoResponseModel>(jsonString);
}
catch (Exception exception) {} return entity;
}

4. Http 系列

4.1 发起请求

使用 HttpWebRequest 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501036.html

使用 WebClient 发起 Http 请求 :https://www.cnblogs.com/MichaelLoveSna/p/14501582.html

使用 HttpClient 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501592.html

使用 HttpClient 发起上传文件、下载文件请求:https://www.cnblogs.com/MichaelLoveSna/p/14501603.html

4.2 接受请求

使用 HttpListener 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501628.html

使用 WepApp 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501612.html

使用 WepApp 处理文件上传、下载请求:https://www.cnblogs.com/MichaelLoveSna/p/14501616.html

C# 应用 - 使用 HttpWebRequest 发起 Http 请求的更多相关文章

  1. C# 应用 - 使用 HttpClient 发起 Http 请求

    1. 需要的库类 \Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.Http.dll System.N ...

  2. C# 应用 - 使用 WebClient 发起 Http 请求

    1. 需要的库类 \Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.dll System.Net.WebCli ...

  3. 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

    原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...

  4. 发起post请求

    string postUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo"; //string req ...

  5. 使用 HttpRequester 更方便的发起 HTTP 请求

    使用 HttpRequester 更方便的发起 HTTP 请求 Intro 一直感觉 .net 里面(这里主要说的是 .net framework 下)发送 HTTP 请求的方式用着不是特别好用,而且 ...

  6. NET MVC全局异常处理(一) 【转载】网站遭遇DDoS攻击怎么办 使用 HttpRequester 更方便的发起 HTTP 请求 C#文件流。 Url的Base64编码以及解码 C#计算字符串长度,汉字算两个字符 2019周笔记(2.18-2.23) Mysql语句中当前时间不能直接使用C#中的Date.Now传输 Mysql中Count函数的正确使用

    NET MVC全局异常处理(一)   目录 .NET MVC全局异常处理 IIS配置 静态错误页配置 .NET错误页配置 程序设置 全局异常配置 .NET MVC全局异常处理 一直知道有.NET有相关 ...

  7. 根据URL发起HTTP请求,我的HTTPHelper。

     完整的demo using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...

  8. .net 模拟发起HTTP请求(用于上传文件)

    用C#在服务端发起http请求,附上代码一 /// <summary> /// 文件帮助类 /// </summary> public class FileHelper { / ...

  9. C#发起Http请求,调用接口

    //方法1. Post 异步请求,普通的异步请求,传输普通的字符串等,对于有html代码的字段值的传输支持不好,如果需要传输html,二进制等数据的传输,请使用下面第二个方法,即使用UploadDat ...

随机推荐

  1. [Angular] 删除旧版本,升级安装最新版本

    目录 删除旧版本 清除未卸载干净的angular-cli缓存 对于Linux 对于Windows 安装最新版本 查看安装版本 创建新项目 删除旧版本 npm uninstall -g angular- ...

  2. SOHO 程序员

    SOHO 程序员:从事程序开发.维护的家居办公人员. 一.自由程序员 SOHO程序员代表一种自由.弹性而新型的工作方式.SOHO,代表一种新经济.新概念. 是一些热爱软件开发的一族. SOHO程序员 ...

  3. Leetcode(15)-三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  4. SpringBoot 全局视角看springboot

    从单体架构到微服务 单体架构 任何一个网站在发布初期几乎都不可能立马就拥有庞大的用户流量和海量数据,都是在不停 的试错过程中一步一步演变其自身架构,满足其自身业务.比如现在能够抗住双十一这么大 流量的 ...

  5. HDU 3920 Clear All of Them I(状压DP)题解

    题意:2n个点,一个起点,开n枪,每枪必须打两个点,花费为起点到其中一点距离加上两点距离.问打完2n个点的最小花费. 思路:很显然应该dp状态,然后枚举i j两个空位置去填,那么复杂度$O(20 * ...

  6. 九种姿势运行Mimikatz

    https://www.freebuf.com/articles/web/176796.html

  7. .NET并发编程-数据结构不可变性

    本系列学习在.NET中的并发并行编程模式,实战技巧 内容目录 .NET不可变集合.NET并发集合函数式数据结构设计一个不可变类 作为程序员经常遇到产品上线后出现各种莫名其妙的问题,在我本地是好好的啊, ...

  8. JVM系列(三):JVM创建过程解析

    上两篇中梳理了整个java启动过程中,jvm大致是如何运行的.即厘清了我们认为的jvm的启动过程.但那里面仅为一些大致的东西,比如参数解析,验证,dll加载等等.把最核心的loadJavaVM()交给 ...

  9. Python对excel的基本操作

    Python对excel的基本操作 目录 1. 前言 2. 实验环境 3. 基本操作 3.1 安装openpyxl第三方库 3.2 新建工作簿 3.2.1 新创建工作簿 3.2.2 缺省工作表 3.2 ...

  10. 吐槽 Apple iPhone 十大反人类的设计 All In One

    吐槽 Apple iPhone 十大反人类的设计 All In One 不支持 GPS 快捷开关 每次都要到,设置> 隐身 > 位置,脑残的设计 顶部的状态栏,网络不支持显示网速 顶部的状 ...