代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
CSharp
】
HTTP网络常用方法封装
作者:
Gordon
/ 发布于
2015/1/26
/
920
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication { class HttpHelper { private System.Net.HttpWebRequest Request = null; private System.Net.WebResponse Response = null; private System.IO.Stream Stream = null; private System.IO.StreamReader Read = null; private System.Byte[] Byte = null; private System.Text.Encoding Encode = System.Text.Encoding.UTF8; private System.Text.RegularExpressions.Match Match = null; /// <summary> /// 公开属性 /// </summary> public System.Net.WebProxy Proxy = new System.Net.WebProxy(); public string IPFor = null; public bool HideInfo = false; public string StrErrorInfo { get; set; } /// <summary> /// 初始化Request /// </summary> /// <param name="Request">对象</param> private void init_Request(ref System.Net.HttpWebRequest Request) { //终端信息 Request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,image/png,application/java-archive,application/java,application/x-java-archive,text/vnd.sun.j2me.app-descriptor,application/vnd.oma.drm.message,application/vnd.oma.drm.content,application/vnd.oma.dd+xml,application/vnd.oma.drm.rights+xml,application/vnd.oma.drm.rights+wbxml,application/x-nokia-widget,text/x-opml,application/vnd.nokia.headwrapper,*/*;q=0.5"; Request.Headers.Add("Accept-Charset", "iso-8859-1,utf-8;q=0.7,*;q=0.7"); Request.Headers.Add("Accept-Language", "zh-cn, zh;q=1.0,en;q=0.5,en;q=0.5,en;q=0.5"); Request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9"); Request.Headers.Add("X-Nokia-MusicShop-Version", "11.0842.9"); //承载方式 Request.Headers.Add("X-Nokia-MusicShop-Bearer", "GPRS/3G"); Request.Headers.Add("X-Nokia-CONNECTION_MODE", "TCP"); Request.Headers.Add("X-Nokia-BEARER", "3G"); Request.Headers.Add("x-up-bear-type", "GPRS/EDGE"); Request.Headers.Add("X-Up-Bearer-Type", "GPRS"); //GGSN信息 Request.Headers.Add("x-source-id", "GZGGSN1101BEr"); Request.Headers.Add("Client-IP", "211.139.151.74"); if (IPFor != null) Request.Headers.Add("x-forwarded-for", IPFor); //网关信息 Request.Headers.Add("Via", "WTP/1.1 192.168.13.33 (Nokia WAP Gateway 4.1/CD1/ECD13_E/4.1.05)"); Request.Headers.Add("X-Nokia-gateway-id", "NWG/4.1/Build4.1.05"); //目标主机 Request.Headers.Add("X-Online-Host", Request.Host); //重要信息 if (!HideInfo) { Request.UserAgent = "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5230/10.0.055; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413"; Request.Headers.Add("x-wap-profile", "http://nds1.nds.nokia.com/uaprof/Nokia5230r100-3G.xml"); if (IPFor != null) { Request.Headers.Add("x-nokia-ipaddress", IPFor); } } //自动重定向 Request.AllowAutoRedirect = false; //代理设置 if (Proxy.Address != null) { Request.Proxy = Proxy; } //其它杂项 Request.KeepAlive = false; Request.Timeout = 8000; } /// <summary> /// 获取网页数据 /// </summary> /// <param name="url">请求地址</param> /// <returns>失败返回null</returns> public string get_Internet(string url, string cookie = null) { try { Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); url = null; if (Request != null) { init_Request(ref Request); if (cookie != null) { Request.Headers.Add("Cookie", cookie); } using (Response = Request.GetResponse()) { Stream = Response.GetResponseStream(); using (Read = new System.IO.StreamReader(Stream, System.Text.Encoding.UTF8)) { url = Read.ReadToEnd(); } Read = null; Stream = null; } Response = null; Request.Abort(); Request = null; } return url; } catch (Exception ex) { StrErrorInfo = ex.Message; return null; } } /// <summary> /// 获取数据流 /// </summary> /// <param name="url">地址</param> /// <param name="Stream">返回数据流</param> /// <returns>失败为false</returns> public bool get_Stream(string url, ref System.IO.MemoryStream Stream, ref string cookie) { try { Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); init_Request(ref Request); if (cookie != null) { Request.Headers.Add("Cookie", cookie); } using (Response = Request.GetResponse()) { Response.GetResponseStream().CopyTo(Stream); if (cookie != null) { cookie += " " + get_Match(Response.Headers.Get("Set-Cookie"), "verifysession=([^;]+);").Replace(";", ""); } } Response = null; } catch (Exception ex) { StrErrorInfo = ex.Message; return false; } if (Request != null) { Request.Abort(); Request = null; } return true; } /// <summary> /// 提交数据并获取返回数据 /// </summary> /// <param name="url">请求地址</param> /// <returns>失败返回null</returns> public string post_Internet(string url, string data, string cookie = null) { try { Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); url = null; if (Request != null) { init_Request(ref Request); if (cookie != null) { Request.Headers.Add("Cookie", cookie); } Request.Method = "POST"; Request.ServicePoint.Expect100Continue = false; Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; Byte = Encode.GetBytes(data); Request.ContentLength = Byte.Length; using (Stream = Request.GetRequestStream()) { Stream.Write(Byte, 0, Byte.Length); } Stream = null; Byte = null; data = null; using (Response = Request.GetResponse()) { Stream = Response.GetResponseStream(); using (Read = new System.IO.StreamReader(Stream)) { url = Read.ReadToEnd(); } Read = null; Stream = null; } Response = null; Request.Abort(); Request = null; } return url; } catch (Exception ex) { StrErrorInfo = ex.Message; return null; } } /// <summary> /// 获取服务器响应报文信息 /// </summary> /// <param name="url">请求地址</param> /// <returns>HTTP响应报文</returns> public string get_All(string url, string cookie = null) { try { Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); url = null; if (Request != null) { Request.Method = "GET"; init_Request(ref Request); if (cookie != null) { Request.Headers.Add("Cookie", cookie); } using (Response = Request.GetResponse()) { foreach (string name in Response.Headers.AllKeys) { url += name + "=" + Response.Headers.Get(name) + "; "; } Stream = Response.GetResponseStream(); using (Read = new System.IO.StreamReader(Stream, System.Text.Encoding.UTF8)) { url += Read.ReadToEnd(); } Read = null; Stream = null; } Response = null; Request.Abort(); Request = null; } return url; } catch (Exception ex) { StrErrorInfo = ex.Message; return null; } } /// <summary> /// 获取服务器返回信息 /// </summary> /// <param name="url">请求地址</param> /// <returns>HTTP Header</returns> public string get_Header(string url, string key = "Set-Cookie", string cookie = null) { try { Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); url = null; if (Request != null) { Request.Method = "HEAD"; init_Request(ref Request); if (cookie != null) { Request.Headers.Add("Cookie", cookie); } using (Response = Request.GetResponse()) { url = Response.Headers.Get(key); } Response = null; Request.Abort(); Request = null; } return url; } catch (Exception ex) { StrErrorInfo = ex.Message; return null; } } /// <summary> /// 获取匹配信息 /// </summary> /// <param name="src">匹配内容</param> /// <returns>正则表达式</returns> public string get_Match(string src, string pattern, string substr = null) { Match = System.Text.RegularExpressions.Regex.Match(src, pattern); if (!Match.Success) { return null; } if (substr != null) { return Match.Groups[substr].Value; } return Match.Value; } /// <summary> /// 发送邮件 /// </summary> /// <param name="ToAddress"></param> /// <param name="Subject"></param> /// <param name="Value"></param> /// <param name="PathArray"></param> /// <returns></returns> public bool try_Email(string ToAddress, string Subject, string Value, string[] PathArray = null) { bool result = false; System.Net.Mail.SmtpClient Mail = new System.Net.Mail.SmtpClient("smtp.qq.com", 25); Mail.UseDefaultCredentials = true; Mail.Credentials = new System.Net.NetworkCredential("feedback01", "z123456"); Mail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; System.Net.Mail.MailMessage Messages = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress("feedback01@qq.com"), new System.Net.Mail.MailAddress(ToAddress)); Messages.BodyEncoding = System.Text.Encoding.UTF8; Messages.SubjectEncoding = System.Text.Encoding.UTF8; Messages.Subject = Subject; Messages.Body = Value; System.Net.Mail.Attachment[] Attachments = null; try { if (PathArray != null) { Attachments = new System.Net.Mail.Attachment[PathArray.Length]; for (int i = 0; i < PathArray.Length; i++) { if (PathArray[i].Length >= 6 && System.IO.File.Exists(PathArray[i])) { Attachments[i] = new System.Net.Mail.Attachment(PathArray[i]); Messages.Attachments.Add(Attachments[i]); } } } Mail.Send(Messages); result = true; } catch (Exception ex) { StrErrorInfo = ex.Message; result = false; } if (Attachments != null) { for (int k = 0; k < Attachments.Length; k++) { if (Attachments[k] != null) { Attachments[k].Dispose(); } } } Messages.Dispose(); Mail.Dispose(); return result; } /// <summary> /// 用于ShellExecuteEx /// </summary> [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct SHELLEXECUTEINFO { public int cbSize; public int fMask; public int hwnd; [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string lpVerb; [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string lpFile; [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string lpParameters; public int lpDirectory; public int nShow; public int hInstApp; public int lpIDList; public int lpClass; public int hkeyClass; public int dwHotKey; public int hIcon; public int hProcess; } /// <summary> /// ShellExecuteEx /// </summary> /// <param name="lpExecInfo"></param> /// <returns></returns> [System.Runtime.InteropServices.DllImport("Shell32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] public static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo); static SHELLEXECUTEINFO ShellInfo; /// <summary> /// 打开URL /// </summary> /// <param name="url"></param> public static void OpenURL(string url) { if (ShellInfo.lpFile == null) { Microsoft.Win32.RegistryKey SubKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command"); if (SubKey == null) { return; } string Explorer = ((string)SubKey.GetValue(null)).Replace("\"", ""); int SpaceOffset = -1; if ((SpaceOffset = Explorer.LastIndexOf(" ")) != -1) { Explorer = Explorer.Substring(0, SpaceOffset); } ShellInfo.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(ShellInfo); ShellInfo.lpFile = Explorer; ShellInfo.nShow = 1; //SW_SHOWNORMAL SubKey.Close(); SubKey.Dispose(); } ShellInfo.lpParameters = url; ShellExecuteEx(ref ShellInfo); } } }
试试其它关键字
HTTP网络
同语言下
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
Gordon
贡献的其它代码
(
28
)
.
图片上传压缩处理
.
拆分文件、合并文件 合并byte数组
.
登录后页面返回到登录之前的页面
.
关闭数据库下所有连接
.
创建实体转换器
.
使用资源文件中的字体,无安装无释放
.
无限多级别分类查询
.
取文件后缀名
.
通过SQL存储过程生成实体类
.
SQL存储过程生成Model层
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3