using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; namespace Utility { /// <summary> /// 通过Http协议访问Web /// </summary> public class HttpClient { #region Cookie集合 /// <summary> /// Cookie集合 /// </summary> private CookieContainer cookies; #endregion #region Http user-agent标头值 /// <summary> /// Http user-agent标头值 /// </summary> public string UserAgent { get; set; } #endregion #region HttpClient构造函数 public HttpClient() { this.cookies = new CookieContainer(); } #endregion #region 获取HttpClient的Cookie集合 /// <summary> /// 获取HttpClient的Cookie集合 /// </summary> /// <returns></returns> public CookieContainer GetCookieContainer() { return this.cookies; } #endregion #region 设置HttpClient的Cookie集合 /// <summary> /// 设置HttpClient的Cookie集合 /// </summary> /// <param name="_cookie">Cookie集合对象</param> /// <returns>True设置成功 False设置失败</returns> public bool SetCookieContainer(CookieContainer _cookie) { if (_cookie != null) { this.cookies = _cookie; return true; } return false; } #endregion #region 以GET方式打开一个Http连接 /// <summary> /// 以GET方式打开一个Http连接 /// </summary> /// <param name="url">地址</param> /// <param name="headers">请求头</param> /// <returns></returns> public ResultResponse OpenGetUrl(string url, Dictionary<string, string> headers) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = this.cookies; request.Method = HttpClient.ConnectionType.GET; request.KeepAlive = true; if (this.UserAgent != null && this.UserAgent != "") { request.UserAgent = this.UserAgent; } this.FillHeaders(request, headers); HttpWebResponse response = request.GetResponse() as HttpWebResponse; return new ResultResponse(response); } #endregion #region 以GET方式打开一个Http连接,302自定义处理行为 /// <summary> /// 以GET方式打开一个Http连接,302自定义处理行为 /// </summary> /// <param name="url">地址</param> /// <param name="headers">请求头</param> /// <param name="action">302跳转处理</param> /// <returns></returns> public ResultResponse OpenGetUrlRedirect(string url, Dictionary<string, string> headers, HttpClient.RedirectAction action) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = this.cookies; request.Method = HttpClient.ConnectionType.GET; request.KeepAlive = true; request.AllowAutoRedirect = false; //302不采用默认行为处理 if (this.UserAgent != null && this.UserAgent != "") { request.UserAgent = this.UserAgent; } this.FillHeaders(request, headers); HttpWebResponse response = request.GetResponse() as HttpWebResponse; ResultResponse result = new ResultResponse(response); if (response.StatusCode == HttpStatusCode.Found) { bool ret = true; if (action != null) { ret = action(result); } string locationurl = response.Headers["Location"]; if (ret == true) { return this.OpenGetUrlRedirect(locationurl, null, action); } return result; } return result; } #endregion #region Http 302跳转处理 /// <summary> /// Http 302跳转处理 /// </summary> /// <param name="result">响应对象</param> /// <returns>False 不继续跳转 True继续跳转</returns> public delegate bool RedirectAction(ResultResponse result); #endregion #region 将Http标头值添加到Request对象中 /// <summary> /// 将Http标头值添加到Request对象中 /// </summary> /// <param name="headers"></param> private void FillHeaders(HttpWebRequest request, Dictionary<string, string> headers) { if (headers != null && headers.Count > 0) { Dictionary<string, string>.Enumerator em = headers.GetEnumerator(); while (em.MoveNext()) { request.Headers.Add(em.Current.Key, em.Current.Value); } } } #endregion #region 以POST方式打开一个Http连接 /// <summary> /// 以POST方式打开一个Http连接 /// </summary> /// <param name="url">地址</param> /// <param name="headers">请求头</param> /// <param name="data">发送的数据</param> /// <returns></returns> public ResultResponse OpenPostUrl(string url, Dictionary<string, string> headers, Dictionary<string, string> data) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = this.cookies; request.Method = HttpClient.ConnectionType.POST; request.KeepAlive = true; if (this.UserAgent != null && this.UserAgent != "") { request.UserAgent = this.UserAgent; } this.FillHeaders(request, headers); byte[] buff = DictToBytes(data); request.GetRequestStream().Write(buff, 0, buff.Length); request.GetRequestStream().Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; return new ResultResponse(response); } #endregion #region 以POST方式打开一个Http连接,302自定义处理行为 /// <summary> /// 以POST方式打开一个Http连接,302自定义处理行为 /// </summary> /// <param name="url">地址</param> /// <param name="headers">请求头</param> /// <param name="data">发送的数据</param> /// <param name="action">302自定义处理</param> /// <returns></returns> public ResultResponse OpenPostUrlRedirect(string url, Dictionary<string, string> headers, Dictionary<string, string> data, HttpClient.RedirectAction action) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = this.cookies; request.Method = HttpClient.ConnectionType.POST; request.KeepAlive = true; request.AllowAutoRedirect = false; if (this.UserAgent != null && this.UserAgent != "") { request.UserAgent = this.UserAgent; } this.FillHeaders(request, headers); byte[] buff = DictToBytes(data); request.GetRequestStream().Write(buff, 0, buff.Length); request.GetRequestStream().Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; ResultResponse result = new ResultResponse(response); if (response.StatusCode == HttpStatusCode.Found) { bool ret = true; if (action != null) { ret = action(result); } string locationurl = response.Headers["Location"]; return result; } return result; } #endregion #region 将字典的key和value拼接成http参数 /// <summary> /// 将字典的key和value拼接成http参数 /// </summary> /// <param name="dic">参数</param> /// <returns></returns> private byte[] DictToBytes(Dictionary<string, string> dic) { StringBuilder sb = null; if (dic != null) { Dictionary<string, string>.Enumerator em = dic.GetEnumerator(); sb = new StringBuilder(); while (em.MoveNext()) { sb.Append(String.Format("{0}={1}&", em.Current.Key, em.Current.Value)); } return System.Text.Encoding.UTF8.GetBytes(sb.ToString()); } return null; } #endregion #region HttpClient打开连接的方式 /// <summary> /// HttpClient打开连接的方式 /// </summary> public static class ConnectionType { public static string GET { get { return "GET"; } } public static string POST { get { return "POST"; } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; namespace Utility { /// <summary> ///包含服务器响应数据的对象 /// </summary> public class ResultResponse { #region HttpWebResponse对象 /// <summary> /// HttpWebResponse对象 /// </summary> private HttpWebResponse m_response; #endregion #region 创建一个HttpWebResponse对象 /// <summary> /// 创建一个HttpWebResponse对象 /// </summary> /// <param name="_response">HttpWebResponse</param> public ResultResponse(HttpWebResponse _response) { this.m_response = _response; } #endregion #region 获取响应内容的二进制流 /// <summary> /// 获取响应内容的二进制流 /// </summary> /// <returns></returns> public Stream GetResponseStream() { if (this.m_response != null) { return this.m_response.GetResponseStream(); } return null; } #endregion #region Http版本 /// <summary> /// Http版本 /// </summary> public string ProtocolVersion { get { return this.m_response != null ? this.m_response.ProtocolVersion.ToString() : ""; } } #endregion /// <summary> /// 响应方法 /// </summary> public string Method { get { return this.m_response != null ? this.m_response.Method : ""; } } /// <summary> /// Http状态码 /// </summary> public string StatusCode { get { return this.m_response != null ? this.m_response.StatusCode.ToString() : ""; } } /// <summary> /// Http响应头 /// </summary> public WebHeaderCollection Headers { get { return this.m_response != null ? this.m_response.Headers : null; } } /// <summary> /// 响应流的字符编码 /// </summary> /// <returns></returns> public Encoding getResponseEncoding() { if (this.m_response != null) { return Encoding.GetEncoding(this.m_response.ContentEncoding); } return null; } /// <summary> /// 获取响应内容的字符串 /// </summary> /// <param name="encoding">字符串编码(默认utf8)</param> /// <returns></returns> public string GetContent(string encoding = "utf-8") { return System.Text.Encoding.GetEncoding(encoding).GetString(this.StreamtoBytes(this.GetResponseStream())); } /// <summary> /// 获取原始的HttpWebResponse /// </summary> /// <returns></returns> public HttpWebResponse GetRawResponse() { return this.m_response; } /// <summary> /// 二进制流转换成字节数组 /// </summary> /// <param name="_stream"></param> /// <returns></returns> private byte[] StreamtoBytes(Stream _stream) { byte[] buff; int rlen; MemoryStream _ms; if (_stream != null) { buff = new byte[1024]; rlen = 0; _ms = new MemoryStream(); while ((rlen = _stream.Read(buff, 0, 1024)) > 0) { _ms.Write(buff, 0, rlen); } buff = _ms.ToArray(); _ms.Close(); _ms.Dispose(); return buff; } return null; } } }
相关推荐
C# Web用户令牌(Token)验证是一种常见的方式,用于防止未经授权的HTTP请求,如GET和POST,确保数据的安全传输。本技术介绍将深入探讨如何使用C#实现令牌验证机制,并结合Nginx集群与SSL证书来增强WebAPI的安全性。...
标题"**C#访问gsoap的webservice**"意味着我们要使用C#语言编写客户端代码,该代码将调用通过gSOAP编译生成的C++ Web服务接口。以下是一般步骤: 1. **生成gSOAP代码**:在服务端,使用gSOAP的wsdl2h工具从Web服务...
标题“C#中客户端通过http协议访问服务端”暗示我们将讨论如何在C#客户端程序中使用HttpClient类。以下是一个简单的示例,展示了如何使用HttpClient发送GET请求到服务端,并接收返回的结果: ```csharp using ...
本篇文章将深入探讨如何使用C#进行POST方法的HTTP接口访问,这对于任何需要与远程服务器交互的应用程序都是至关重要的。POST请求常用于向服务器发送数据,如表单提交或API调用。 首先,理解HTTP协议的基础是必要的...
C#访问domino,通过http访问Domino,C#快速访问Domino,C#集成lotus domino 完全提供源码 界面请查阅 https://blog.csdn.net/weijia3624/article/details/113108704
在这个场景下,“c# rest http请求类库”指的是用于处理RESTful HTTP请求的工具,例如著名的第三方库RestSharp。 RestSharp是一个强大的、轻量级的C# HTTP客户端库,它提供了简单易用的API来发送RESTful请求并处理...
### C# 访问URL接口进行调用代码实例解析 #### 概述 在现代软件开发中,HTTP请求是客户端与服务器端交互的基础之一。本文将深入探讨如何使用C#语言来实现对URL接口的访问,并通过具体示例代码来展示这一过程。此...
HTTPS(全称:Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全...资源主要是讲解:c#采用https访问Web服务器的编程方法,以及源代码实现Https证书认证的过程。
标题中的“自己封装的C#实现HTTP请求的动态链接库,dll”指的是使用C#编程语言编写的HTTP客户端库,该库被封装成一个动态链接库(DLL)文件,供其他应用程序调用,以实现HTTP协议的网络通信功能。DLL是一种可重用的...
在IT行业中,HTTP代理是一种网络通信机制,它允许客户端(如Web浏览器)通过另一台服务器作为中介来访问互联网上的资源。这种技术常用于提高匿名性、优化网络性能或绕过特定的网络限制。本篇文章将深入探讨如何使用...
在描述中提到的“HTTP基本操作”是指使用C#对HTTP协议的应用。HTTP(超文本传输协议)是互联网上应用最广泛的一种网络协议,用于从万维网服务器传输超文本到本地浏览器。在C#中,可以使用`System.Net`命名空间的类来...
4. **网络请求**:访问网页通常需要用到HTTP协议,C#提供了`System.Net.WebClient`或`HttpClient`类来发送HTTP请求。源码中,开发者可能使用了其中一个类来发送GET请求到设定的URL,获取网页内容。 5. **异步编程**...
### Windows 下安装 Cassandra 与 C# 访问配置 #### 安装 Cassandra 在 Windows 平台上安装 Apache Cassandra 的步骤如下: 1. **下载 Cassandra** 首先访问官方站点 [http://cassandra.apache.org/]...
它允许开发者创建可被HTTP客户端(如浏览器、手机应用等)访问的API。 - **控制器**:Web API的核心是控制器,它继承自`ApiController`类,负责处理HTTP请求并返回响应。 - **路由配置**:定义URL模式与控制器方法...
c# http请求webapi接口封装类
标题 "C# OPC 转HTTP的restful访问" 描述了如何在C#编程环境中,利用OPC(OLE for Process Control)技术并通过RESTful API实现HTTP协议的转换与访问。OPC是一种标准接口,主要用于工业自动化设备和软件之间的数据...
本示例介绍的是如何使用Java来访问由C#编写的WebService服务。WebService是一种基于互联网的、平台无关的通信机制,它允许不同系统间的应用程序通过网络进行交互。 首先,我们需要理解WebService的基本原理。...
C#桌面程序 winform WPF集成内置WebApi C# 创建HTTP Web API服务,winform WPF项目创建HTTP WEB服务,不使用IIS业务 WPF WebApi 限权限访问 在维护旧的项目时,有时需要提供APP连接的需求,就要提供HTTP服务,...
7. **操作系统交互**:C#的System.Diagnostics命名空间允许与操作系统进行交互,如Process类用于启动和管理进程,Environment类提供了系统属性访问,如操作系统版本和环境变量。 8. **网络编程**:C#的System.Net...
以上是使用C#访问中维摄像机的关键知识点。通过理解这些概念,你可以构建一个简单的应用来连接、浏览和记录来自中维摄像机的视频。然而,实际的实现将取决于中维摄像机提供的具体API和你的具体需求。记得在开发过程...