C# HTTP网络常用方法封装
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Register
- {
- public class HttpClass
- {
- 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;
- /// <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;
- }
- // public void GZipDecompress(ref System.IO.Stream refStream)
- // {
- // using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
- // {
- // using (System.IO.Compression.GZipStream gZip = new System.IO.Compression.GZipStream(refStream, System.IO.Compression.CompressionMode.Decompress, true))
- // {
- // System.IO.BinaryReader reader = new System.IO.BinaryReader(gZip);
- // System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
- // while (true)
- // {
- // char[] p = reader.ReadChars(32);
- // byte[] buffer = reader.ReadBytes(32);
- // if (buffer == null || buffer.Length < 1) break;
- // writer.Write(buffer);
- // }
- // writer.Close();
- // gZip.CopyTo(stream);
- // }
- // stream.CopyTo(refStream);
- // }
- // }
- /// <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)
- {
- Error.Write(ref ex);
- 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)
- {
- Error.Write(ref ex);
- 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)
- {
- Error.Write(ref ex);
- 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)
- {
- Error.Write(ref ex);
- 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)
- {
- Error.Write(ref ex);
- 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 static 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)
- {
- Error.Write(ref ex);
- 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);
- }
- }
- }
C# HTTP网络常用方法封装的更多相关文章
- java Map常用方法封装
java Map常用方法封装 CreationTime--2018年7月16日15点59分 Author:Marydon 1.准备工作 import java.util.HashMap; impo ...
- 上门洗车APP --- Androidclient开发 之 网络框架封装介绍(二)
上门洗车APP --- Androidclient开发 之 网络框架封装介绍(二) 前几篇博文中给大家介绍了一下APP中的基本业务及开发本项目使用的网络架构: 上门洗车APP --- Androidc ...
- Android OkHttp网络连接封装工具类
package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...
- React-Native 之 GD (八)GET 网络请求封装
1.到这里,相信各位对 React-Native 有所熟悉了吧,从现在开始我们要慢慢往实际的方向走,这边就先从网络请求这部分开始,在正式开发中,网络请求一般都单独作为一部分,我们在需要使用的地方只需要 ...
- HttpClient 常用方法封装
简介 在平时写代码中,经常需要对接口进行访问,对于 http 协议 rest 风格的接口请求,大多使用 HttpClient 工具进行编写,想着方便就寻思着把一些常用的方法进行封装,便于平时快速的使用 ...
- flutter dio网络请求封装实现
flutter dio网络请求封装实现 文章友情链接: https://juejin.im/post/6844904098643312648 在Flutter项目中使用网络请求的方式大致可分为两种 ...
- 十. Axios网络请求封装
1. 网络模块的选择 Vue中发送网络请求有非常多的方式,那么在开发中如何选择呢? 选择一:传统的Ajax是基于XMLHttpRequest(XHR) 为什么不用它呢?非常好解释配置和调用方式等非常混 ...
- iOS开发——post异步网络请求封装
IOS中有许多网络请求的函数,同步的,异步的,通过delegate异步回调的. 在做一个项目的时候,上网看了很多别人的例子,发现都没有一个简单的,方便的异步请求的封装例子.我这里要给出的封装代码,是异 ...
- iOS开发-网络-合理封装请求接口
概述 如今大多App都会与网络打交道,作为开发者,合理的对网络后台请求接口进行封装十分重要.本文要介绍的就是一种常见的采用回调函数(方法)的网络接口封装,也算的是一种构架吧. 这个构架主要的idea是 ...
随机推荐
- Java - 手动解析不带引号的JSON字符串
目录 1 需求说明 2 解析代码 2.1 实现思路 2.2 详细代码 2.3 测试样例 1 需求说明 项目中遇到了一批不带引号的类JSON格式的字符串: {Name:Heal,Age:20,Tag:[ ...
- python之“装饰器”
在python里装饰器 其定义:装饰器就是一个函数,用来装饰其他函数,就是给其他函数添加功能. 装饰器有两个特点: 1.装饰器不修改被装饰函数的源码: 2.装饰器不锈钢被装饰函数的调用方式. 在编程中 ...
- Flink集群Standalone启动脚本(源码分析)
整个Flink集群的角色分为Jobmanager和TaskManager 以Standalone为例来看一下脚本里面是怎样启动集群的 找到源码的dist这里面包含了启动的脚本文件 standalone ...
- Python学习 之三 Python基础&运算符
第三章:Python基础 & 运算符 3.1 内容回顾 & 补充 计算机基础 编码 字符串: "中国" "Hello" 字 符: 中 e 字 节 ...
- JVM(十三):后端编译优化
JVM(十三):后端编译优化 在 JVM(一):源文件的转变 中我们介绍了 Java 中的前端优化,即将 Java 源代码转换为字节码文件.在本文中,我们将介绍字节码文件如何转换为本地机器码,并如何对 ...
- 设计模式(C#)——11代理模式
推荐阅读: 我的CSDN 我的博客园 QQ群:704621321 前言 在软件开发过程中,当无法直接访问某个对象或访问某个对象存在困难时,我们希望可以通过一个中介来间接访问,这就是 ...
- HDU 6319
题意略. 思路:倒着使用单调队列,大的放在前,小的放在后. 详见代码: #include<bits/stdc++.h> using namespace std; typedef long ...
- Mysql系列 - 第3天:管理员必备技能(必须掌握)
这是mysql系列第3篇文章. 环境:mysql5.7.25,cmd命令中进行演示. 在玩mysql的过程中,经常遇到有很多朋友在云上面玩mysql的时候,说我创建了一个用户为什么不能登录?为什么没有 ...
- 运行git提示xcrun: error: invalid active developer path错误
运行git提示xcrun: error: invalid active developer path错误 是xcode的原因 运行如下命令解决: xcode-select --install
- 2019DX#1
1001 Blank 题意 有一个长度为n(n<=100)的位子,填入四种颜色,有m个限制,某个区间的颜色个数要恰好等于x个.问颜色个数的方案数. 思路 DP 四维的DP,利用滚动数组优化一维空 ...