C# Http请求(GET/HTTP/HTTPS)

简介: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Net.Security;  
using System.Security.Cryptography.X509Certificates;  
using System.DirectoryServices.Protocols;  
using System.ServiceModel.Security;  
using System.Net;  
using System.IO;  
using System.IO.Compression;  
using System.Text.RegularExpressions;  

namespace BaiduCang  
{  
   /// <summary>  
   /// 有关HTTP请求的辅助类  
   /// </summary>  
   public class HttpWebResponseUtility  
   {  
       private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";  
       /// <summary>  
       /// 创建GET方式的HTTP请求  
       /// </summary>  
       /// <param name="url">请求的URL</param>  
       /// <param name="timeout">请求的超时时间</param>  
       /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
       /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
       /// <returns></returns>  
       public static HttpWebResponse CreateGetHttpResponse(string url,int? timeout, string userAgent,CookieCollection cookies)  
       {  
           if (string.IsNullOrEmpty(url))  
           {  
               throw new ArgumentNullException("url");  
           }  
           HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;  
           request.Method = "GET";  
           request.UserAgent = DefaultUserAgent;  
           if (!string.IsNullOrEmpty(userAgent))  
           {  
               request.UserAgent = userAgent;  
           }  
           if (timeout.HasValue)  
           {  
               request.Timeout = timeout.Value;  
           }  
           if (cookies != null)  
           {  
               request.CookieContainer = new CookieContainer();  
               request.CookieContainer.Add(cookies);  
           }  
           return request.GetResponse() as HttpWebResponse;  
       }  
       /// <summary>  
       /// 创建POST方式的HTTP请求  
       /// </summary>  
       /// <param name="url">请求的URL</param>  
       /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
       /// <param name="timeout">请求的超时时间</param>  
       /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
       /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
       /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
       /// <returns></returns>  
       public static HttpWebResponse CreatePostHttpResponse(string url,IDictionary<string,string> parameters,int? timeout, string userAgent,Encoding requestEncoding,CookieCollection cookies)  
       {  
           if (string.IsNullOrEmpty(url))  
           {  
               throw new ArgumentNullException("url");  
           }  
           if(requestEncoding==null)  
           {  
               throw new ArgumentNullException("requestEncoding");  
           }  
           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";  
             
           if (!string.IsNullOrEmpty(userAgent))  
           {  
               request.UserAgent = userAgent;  
           }  
           else 
           {  
               request.UserAgent = DefaultUserAgent;  
           }  

           if (timeout.HasValue)  
           {  
               request.Timeout = timeout.Value;  
           }  
           if (cookies != null)  
           {  
               request.CookieContainer = new CookieContainer();  
               request.CookieContainer.Add(cookies);  
           }  
           //如果需要POST数据  
           if(!(parameters==null||parameters.Count==0))  
           {  
               StringBuilder buffer = new StringBuilder();  
               int i = 0;  
               foreach (string key in parameters.Keys)  
               {  
                   if (i > 0)  
                   {  
                       buffer.AppendFormat("&{0}={1}", key, parameters[key]);  
                   }  
                   else 
                   {  
                       buffer.AppendFormat("{0}={1}", key, parameters[key]);  
                   }  
                   i++;  
               }  
               byte[] data = requestEncoding.GetBytes(buffer.ToString());  
               using (Stream stream = request.GetRequestStream())  
               {  
                   stream.Write(data, 0, data.Length);  
               }  
           }  
           return request.GetResponse() as HttpWebResponse;  
       }  

       private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)  
       {  
           return true; //总是接受  
       }  
   }  
}

 

相关文章
|
10月前
|
JSON 监控 API
掌握使用 requests 库发送各种 HTTP 请求和处理 API 响应
本课程全面讲解了使用 Python 的 requests 库进行 API 请求与响应处理,内容涵盖环境搭建、GET 与 POST 请求、参数传递、错误处理、请求头设置及实战项目开发。通过实例教学,学员可掌握基础到高级技巧,并完成天气查询应用等实际项目,适合初学者快速上手网络编程与 API 调用。
960 130
|
11月前
|
Android开发 Kotlin
|
11月前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
890 2
|
11月前
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
11月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
12月前
|
缓存 JavaScript 前端开发
Vue 3 HTTP请求封装导致响应结果无法在浏览器中获取,尽管实际请求已成功。
通过逐项检查和调试,最终可以定位问题所在,修复后便能正常在浏览器中获取响应结果。
418 0
|
12月前
|
Go
如何在Go语言的HTTP请求中设置使用代理服务器
当使用特定的代理时,在某些情况下可能需要认证信息,认证信息可以在代理URL中提供,格式通常是:
736 0
|
缓存 安全 网络协议
HTTP和HTTPS的区别有哪些?
本文简要总结了 HTTP 和 HTTPS 的区别,从概念、端口、连接方式、使用场景、安全性等多个角度进行了对比。HTTP 是无状态的、无连接的应用层协议,适用于一般性网站和性能要求较高的应用;HTTPS 则通过 SSL/TLS 层提供加密、认证和完整性保护,适用于涉及敏感信息和高安全性的场景。文章还讨论了两者在性能上的差异,包括握手和加密开销、缓存效果以及 HTTP/2 的多路复用技术。最终,根据具体需求选择合适的协议能够更好地平衡安全性和性能。
18463 2
HTTP和HTTPS的区别有哪些?
|
安全 网络安全 数据安全/隐私保护
HTTP 与 HTTPS 协议及 SSL 证书解析-http和https到底有什么区别?-优雅草卓伊凡
HTTP 与 HTTPS 协议及 SSL 证书解析-http和https到底有什么区别?-优雅草卓伊凡
828 3
|
安全 网络协议 网络安全
IP代理的三大协议:HTTP、HTTPS与SOCKS5的区别
**HTTP代理**适用于基本网页浏览,简单但不安全;**HTTPS代理**提供加密,适合保护隐私;**SOCKS5代理**灵活强大,支持TCP/UDP及认证,适用于绕过限制。选择代理协议应考虑安全、效率及匿名需求。