WPF带cookie get/post请求网页,下载文件,图片,可保持会话状态
直接写成啦一个MyNet.cs类方便使用
get/post方法请求
//get请求
MyNet.SendRequest("http://www.baidu.com");
//post请求
var param = new Dictionary<string, string>
{
{"a","this is a param" },
{"b","this second param"}
};
MyNet.SendRequest("http://www.baidu.com",param);
//后面有参数自动转为post,没有参数默认为get
设置请求头
var headers = new Dictionary<string, string>() {
{"UserAgent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36" }
};
MyNet.SendRequest("http://www.baidu.com",param,headers);
带cookie请求
如果需要带cookies请求的话就在发送请求之前添加cookie(可以直接从浏览器中复制出来放进去)
MyNet.m_cookie = MyNet.FormatCookies("thw=us; miid=417871058341351592; ali_ab=123.160.175.149.1488949082923.4; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; v=0;", ".taobao.com");
String str = MyNet.SendRequest("https://myseller.taobao.com/seller_admin.htm");
保持会话状态(保持cookie不丢失)
在请求之前设置如下
MyNet.m_sessionStatus=true;//默认为false不保持会话
下载文件
最后一个参数为下载的进度条显示,如果不需要可以不填写
<ProgressBar Name="jindu" Width="200"></ProgressBar>
MyNet.DownloadFile("http://sw.bos.baidu.com/sw-search-sp/software/1c5131aea1842/ChromeStandalone_56.0.2924.87_Setup.exe", "d:/a.exe",jindu);
下面是类文件直接复制保存为MyNet.cs即可
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Security.Permissions;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Web;
namespace Ank.Class
{
class MyNet
{
//是否保持会话状态
public static bool m_sessionStatus = false;
//请求时要带上的cookie
public static CookieCollection m_cookie = null;
//代理服务器信息格式为: [主机:端口,用户名,密码];
public static string[] m_proxy = null;
private static Log m_log = Log.getInstance();
public delegate void ProgressBarSetter(double value);
/**
* 添加cookie字符串
* s cookie字符串
* defaultDomain cookie域
* */
public static CookieCollection FormatCookies(string s, string defaultDomain)
{
s = s.Replace(",", "%2C");
CookieCollection cc = new CookieCollection();
if (string.IsNullOrEmpty(s) || s.Length < || s.IndexOf("=") < ) return cc;
if (string.IsNullOrEmpty(defaultDomain) || defaultDomain.Length < ) return cc;
s.TrimEnd(new char[] { ';' }).Trim();
//Uri urI = new Uri(defaultDomain);
//defaultDomain = urI.Host.ToString();
//用软件截取的cookie会带有expires,要把它替换掉
if (s.IndexOf("expires=") >= )
{
s = Replace(s, @"expires=[\w\s,-:]*GMT[;]?", "");
}
//只有一个cookie直接添加
if (s.IndexOf(";") < )
{
System.Net.Cookie c = new System.Net.Cookie(s.Substring(, s.IndexOf("=")), s.Substring(s.IndexOf("=") + ));
c.Domain = defaultDomain;
cc.Add(c);
return cc;
}
//不同站点与不同路径一般是以英文道号分别
if (s.IndexOf(",") > )
{
s.TrimEnd(new char[] { ',' }).Trim();
foreach (string s2 in s.Split(','))
{
cc = FormatCookies(s2, defaultDomain, cc);
}
return cc;
}
else //同站点与同路径,不同.Name与.Value
{
return FormatCookies(s, defaultDomain, cc);
}
}
//添加到CookieCollection集合部分
private static CookieCollection FormatCookies(string s, string defaultDomain, CookieCollection cc)
{
try
{
s.TrimEnd(new char[] { ';' }).Trim();
System.Collections.Hashtable hs = new System.Collections.Hashtable();
foreach (string s2 in s.Split(';'))
{
string s3 = s2.Trim();
if (s3.IndexOf("=") > )
{
string[] s4 = s3.Split('=');
hs.Add(s4[].Trim(), s4[].Trim());
}
}
string defaultPath = "/";
foreach (object Key in hs.Keys)
{
if (Key.ToString().ToLower() == "path")
{
defaultPath = hs[Key].ToString();
}
else if (Key.ToString().ToLower() == "domain")
{
defaultDomain = hs[Key].ToString();
}
}
foreach (object Key in hs.Keys)
{
if (!string.IsNullOrEmpty(Key.ToString()) && !string.IsNullOrEmpty(hs[Key].ToString()))
{
if (Key.ToString().ToLower() != "path" && Key.ToString().ToLower() != "domain")
{
Cookie c = new Cookie();
c.Name = Key.ToString();
c.Value = hs[Key].ToString();
c.Path = defaultPath;
c.Domain = defaultDomain;
cc.Add(c);
}
}
}
}
catch(Exception ex) {
errorMsg(ex);
}
return cc;
}
private static string Replace(string strSource, string strRegex, string strReplace)
{
try
{
Regex r;
r = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
string s = r.Replace(strSource, strReplace);
return s;
}
catch
{
return strSource;
}
}
/**
* 创建一个请求
* */
private static HttpWebRequest CreateRequest(string url = "", Dictionary<string, string> headers = null)
{
HttpWebRequest httpRequest;
CookieContainer cookieCon = new CookieContainer();
if (m_cookie != null && m_cookie.Count > )
{
cookieCon.Add(new Uri(url), m_cookie);
}
httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Timeout = ;
//添加代理访问
if (m_proxy != null && m_proxy.Length > )
{
WebProxy proxy = new WebProxy();
proxy.Address = new Uri(m_proxy[]);
if (m_proxy.Length == )
{
proxy.Credentials = new NetworkCredential(m_proxy[], m_proxy[]);
httpRequest.UseDefaultCredentials = true;
}
httpRequest.Proxy = proxy;
}
//如果有请求头的话加上请求头
if (headers != null)
{
WebHeaderCollection hds = new WebHeaderCollection();
foreach (var item in headers.Keys)
{
hds.Add(item, headers[item]);
}
httpRequest.Headers = hds;
}
//如果有cookie就加上cookie
httpRequest.CookieContainer = cookieCon;
return httpRequest;
}
/**
* 从图片地址下载图片到本地磁盘
* filePath 保存的路径
* url图片地址
**/
public static bool DownImage( string url,string filePath, Dictionary<string, string> headers = null)
{
bool Value = false;
WebResponse response = null;
HttpWebRequest request = null;
Stream stream = null;
try
{
request = CreateRequest(url, headers);
response = request.GetResponse();
stream = response.GetResponseStream();
if (!response.ContentType.ToLower().StartsWith("text/"))
{
Value = SaveBinaryFile(response, filePath);
}
}
catch (Exception ex)
{
errorMsg(ex);
}
return Value;
}
/**
* 将二进制文件保存到磁盘
* response 响应数据
* filePath 保存的文件路径
**/
private static bool SaveBinaryFile(WebResponse response, string filePath)
{
bool Value = true;
byte[] buffer = new byte[];
try
{
if (File.Exists(filePath))
File.Delete(filePath);
Stream outStream = System.IO.File.Create(filePath);
Stream inStream = response.GetResponseStream();
int l;
do
{
l = inStream.Read(buffer, , buffer.Length);
if (l > )
outStream.Write(buffer, , l);
}
while (l > );
outStream.Close();
inStream.Close();
}
catch (Exception ex)
{
errorMsg(ex);
Value = false;
}
return Value;
}
/**
* 下载文件到本地
* url 文件url地址,这里的路径要用双斜杠
* filePath 本地保存文件路径
* bar进度条
**/
public static void DownloadFile(string url, string filePath, ProgressBar bar = null, Dictionary<string, string> headers = null)
{
try
{
//去操作ui线程元素
bar.Dispatcher.BeginInvoke(new Action(() =>
{
if (bar != null)
{
bar.Value = bar.Minimum;
}
}));
HttpWebRequest req = CreateRequest(url, headers);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
long totalBytes = resp.ContentLength;
bar.Dispatcher.BeginInvoke(new Action(() =>
{
if (bar != null)
{
bar.Maximum = (int)totalBytes;
}
}));
using (Stream sResp = resp.GetResponseStream())
{
filePath = filePath.Replace("\\", "/");
if (!Directory.Exists(filePath.Substring(, filePath.LastIndexOf('/'))))
{
Directory.CreateDirectory(filePath.Substring(, filePath.LastIndexOf('/')));
}
using (Stream sFile = new FileStream(filePath, FileMode.Create))
{
long totalDownloadBytes = ;
byte[] bs = new byte[];
int size = sResp.Read(bs, , bs.Length);
while (size > )
{
totalDownloadBytes += size;
DispatcherHelper.DoEvents();
sFile.Write(bs, , size);
bar.Dispatcher.BeginInvoke(new Action(() =>
{
if (bar != null)
{
bar.Value = (int)totalDownloadBytes;
}
}));
Console.WriteLine((int)totalDownloadBytes);
size = sResp.Read(bs, , bs.Length);
}
}
}
bar.Dispatcher.BeginInvoke(new Action(() =>
{
if (bar != null)
{
bar.Value = bar.Maximum;
}
}));
}
catch (Exception ex)
{
errorMsg(ex);
}
}
public static string http_build_query(Dictionary<string, string> dict = null)
{
if (dict == null)
{
return "";
}
var builder = new UriBuilder();
var query = HttpUtility.ParseQueryString(builder.Query);
foreach (var item in dict.Keys)
{
query[item] = dict[item];
}
return query.ToString().Trim('?').Replace("+", "%20");
}
#region //post数据
/**
* 发送请求,如果有postdata自动转换为post请求
* */
public static string SendRequest(string url, Dictionary<string, string> postData = null, Dictionary<string, string> headers = null, string encode = "utf-8")
{
string rehtml = "";
HttpWebRequest httpRequest = null;
WebResponse response = null;
try
{
Encoding encoding = Encoding.GetEncoding(encode);
httpRequest = CreateRequest(url, headers);
//如果有请求数据就改成post请求
if (postData != null && postData.Count != )
{
var parstr = http_build_query(postData);
byte[] bytesToPost = encoding.GetBytes(parstr);
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Method = "POST";
httpRequest.ContentLength = bytesToPost.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytesToPost, , bytesToPost.Length);
requestStream.Close();
}
else
{
httpRequest.Method = "GET";
}
response = httpRequest.GetResponse();
//从响应头自动判断网页编码
//Content - Type:text / html; charset = utf - 8
string contentType = response.Headers["Content-Type"];
//Encoding encoding = null;
Regex regex = new Regex("charset\\s*=\\s*(\\S+)", RegexOptions.IgnoreCase);
Match match = null;
if (contentType != null)
{
match = regex.Match(contentType);
//在响应头中找到编码声明
if (match.Success)
{
//找到页面里的编码声明,就按编码转换
try
{
encoding = Encoding.GetEncoding(match.Groups[].Value.Trim());
using (TextReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
rehtml = reader.ReadToEnd();
}
}
catch (Exception ex)
{
errorMsg(ex);
rehtml = "";
}
}
}
//响应头类型为空或没有找到编码声明的情况,直接从响应内容中找编码声明
using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
rehtml = reader.ReadToEnd();
regex = new Regex("<\\s*meta.+charset\\s*=\\s*(\\S+)\\s*\"", RegexOptions.IgnoreCase);
match = regex.Match(rehtml);
//找到编码声明就转码,找不到拉倒,不管啦
if (match.Success)
{
try
{
encoding = Encoding.GetEncoding(match.Groups[].Value.Trim());
rehtml = encoding.GetString(Encoding.Default.GetBytes(rehtml));
// Console.WriteLine(str);
}
catch (Exception ex)
{
errorMsg(ex);
//转码出错,原样返回,不管它是啥东西,不处理啦
}
}
}
}
catch (Exception ex)
{
errorMsg(ex);
rehtml = "";
}
if (m_sessionStatus)
{
m_cookie = httpRequest.CookieContainer.GetCookies(new Uri(url));
}
else
{
m_cookie = null;
}
httpRequest = null;
if (response != null)
{
response.Dispose();
response = null;
}
return rehtml;
#endregion
}
private static void errorMsg(Exception ex = null)
{
if (ex != null)
{
Console.WriteLine(ex.Message);
m_log.write(ex.Message, "litedb");
m_log.write(ex.ToString(), "litedb");
}
}
public static class DispatcherHelper
{
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame);
try { Dispatcher.PushFrame(frame); }
catch (InvalidOperationException) { }
}
private static object ExitFrames(object frame)
{
((DispatcherFrame)frame).Continue = false;
return null;
}
}
}
}
WPF带cookie get/post请求网页,下载文件,图片,可保持会话状态的更多相关文章
- postman发送带cookie的http请求
1:需求:测试接口的访问权限,对于某些接口A可以访问,B不能访问. 2:问题:对于get请求很简单,登录之后,直接使用浏览器访问就可以: 对于post请求的怎么测试呢?前提是需要登录态,才能访问接口. ...
- urllib2 post请求方式,带cookie,添加请求头
#encoding = utf-8 import urllib2import urllib url = 'http://httpbin.org/post'data={"name": ...
- 在unity 中,使用http请求,下载文件到可读可写路径
在这里我用了一个线程池,线程池参数接收一个带有object参数的,无返回值的委托 ,下载用到的核心代码,网上拷贝的,他的核心就是发起一个web请求,然后得到请求的响应,读取响应的流 剩下的都是常见的I ...
- ajax请求不能下载文件(转载)
最近在做文件下载,后台写了个控制层,直接走进去应该就可以下载文件,各种文件图片,excel等 但是起初老是下载失败,并且弹出下面的乱码: 前台请求代码: $('#fileexcel').unbind( ...
- ajax请求无法下载文件的原因
原因: Ajax下载文件的这种方式本来就是禁止的.出于安全因素的考虑,javascript是不能够保存文件到本地的, 所以ajax考虑到了这点,只是接受json,text,html,xml格式的返回值 ...
- axios通过post请求下载文件/图片
我们平常下载文件一般都是通过get请求直接访问进行下载, 但是当有特殊情况如权限控制之类的会要求我们通过post请求进行下载,这时就不一样了, 具体方法是通过协调后端,约定返回的文件流,请求的resp ...
- [iOS AFNetworking框架实现HTTP请求、多文件图片上传下载]
简单的JSON的HTTP传输就不说了,看一个简单的DEMO吧. 主要明白parameters是所填参数,类型是字典型.我把这部分代码封装起来了,以便多次调用.也许写在一起更清楚点. #pragma m ...
- 通过PHP CURL模拟请求上传文件|图片。
现在有一个需求就是在自己的服务器上传图片到其他服务器上面,过程:客户端上传图片->存放到本地服务器->再转发到第三方服务器; 由于前端Ajax受限制,只能通过服务器做转发了. 在PHP中通 ...
- 使用js实现点击按钮下载文件
有时候我们在网页上需要增加一个下载按钮,让用户能够点击后下载页面上的资料,那么怎样才能实现功能呢?这里有两种方法: 现在需要在页面上添加一个下载按钮,点击按钮下载文件. 题外话,这个下载图标是引用的 ...
随机推荐
- Python 33(2)进程理论
一:什么是进程 进程指的是一个正在进行 / 运行的程序,进程是用来描述程序执行过程的虚拟概念 进程vs程序 程序:一堆代码 进程:程序的执行的过程 进程的概念起源于操作系统,进程是操作 ...
- LeetCode刷题 1. Two Sum 两数之和 详解 C++语言实现 java语言实现
1. Two Sum 两数之和 Given an array of integers, return indices of the two numbers such that they add up ...
- POJ 3481 set水过
题意:1表示插入客户K,他的优先级是P(相当于大小),2表示输出当前优先级最高的客户(即找出最大值),并且删除.3同理输出最低级的. 这题可以用splay treap AVL SBT -- (可是我并 ...
- Oracle调整内存参后报ORA-00844和ORA-00851
数据库服务器内存由16G增加为64G,为充分利用内存资源,对Oracle内存参数做了如下调整: SQL>alter system set sga_max_size=40960M scope=sp ...
- Oracle update时做表关联
感觉还是sqlserver中的写法比较好理解,Oracle的写法都快把我搞晕了, 注意: 1.要修改的表,不要加入到子查询中,用别名在子查询中与其他表进行关联即可. 2.exsits不能少,exsit ...
- [转]line-height1.5和line-height:150%的区别
line-height1.5和line-height:150%的区别 一.区别 区别体现在子元素继承时,如下: 父元素设置line-height:1.5会直接继承给子元素,子元素根据自己的font ...
- C# Socket发送接收字节数组和十六16进制之间转换函数
近期在使用远程网络模块的时候, 需要用的Socket发送数据,远程模块指令为16进制. 官方提供的DEMO比较繁琐.不方便新手使用. 下面的转换函数可大大方便新手使用. // 16进制字符串转字节数组 ...
- java就业前景发展方向分析
随着信息化的发展,IT培训受倒了越来越多人的追捧.在开发领域,JAVA培训成为了许多人的首选!java拥有强大的开发者的数量已超过了之前的900万,将近97%的企业电脑也在运行着java,其下载量每年 ...
- 时序分析:HMM模型(状态空间)
关于HMM模型:时序分析:隐马尔科夫模型 HMM用于手势识别: 训练时每一种手势对应一个HMM-Model,识别率取最大的一个HMM即可. 类似于一个封装的完成多类识别器功能单层网络. 优点: 尤其 ...
- [Intermediate Algorithm] - Steamroller
题目 对嵌套的数组进行扁平化处理.你必须考虑到不同层级的嵌套. 提示 Array.isArray() 测试用例 steamroller([[["a"]], [["b&qu ...