直接写成啦一个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请求网页,下载文件,图片,可保持会话状态的更多相关文章

  1. postman发送带cookie的http请求

    1:需求:测试接口的访问权限,对于某些接口A可以访问,B不能访问. 2:问题:对于get请求很简单,登录之后,直接使用浏览器访问就可以: 对于post请求的怎么测试呢?前提是需要登录态,才能访问接口. ...

  2. urllib2 post请求方式,带cookie,添加请求头

    #encoding = utf-8 import urllib2import urllib url = 'http://httpbin.org/post'data={"name": ...

  3. 在unity 中,使用http请求,下载文件到可读可写路径

    在这里我用了一个线程池,线程池参数接收一个带有object参数的,无返回值的委托 ,下载用到的核心代码,网上拷贝的,他的核心就是发起一个web请求,然后得到请求的响应,读取响应的流 剩下的都是常见的I ...

  4. ajax请求不能下载文件(转载)

    最近在做文件下载,后台写了个控制层,直接走进去应该就可以下载文件,各种文件图片,excel等 但是起初老是下载失败,并且弹出下面的乱码: 前台请求代码: $('#fileexcel').unbind( ...

  5. ajax请求无法下载文件的原因

    原因: Ajax下载文件的这种方式本来就是禁止的.出于安全因素的考虑,javascript是不能够保存文件到本地的, 所以ajax考虑到了这点,只是接受json,text,html,xml格式的返回值 ...

  6. axios通过post请求下载文件/图片

    我们平常下载文件一般都是通过get请求直接访问进行下载, 但是当有特殊情况如权限控制之类的会要求我们通过post请求进行下载,这时就不一样了, 具体方法是通过协调后端,约定返回的文件流,请求的resp ...

  7. [iOS AFNetworking框架实现HTTP请求、多文件图片上传下载]

    简单的JSON的HTTP传输就不说了,看一个简单的DEMO吧. 主要明白parameters是所填参数,类型是字典型.我把这部分代码封装起来了,以便多次调用.也许写在一起更清楚点. #pragma m ...

  8. 通过PHP CURL模拟请求上传文件|图片。

    现在有一个需求就是在自己的服务器上传图片到其他服务器上面,过程:客户端上传图片->存放到本地服务器->再转发到第三方服务器; 由于前端Ajax受限制,只能通过服务器做转发了. 在PHP中通 ...

  9. 使用js实现点击按钮下载文件

    有时候我们在网页上需要增加一个下载按钮,让用户能够点击后下载页面上的资料,那么怎样才能实现功能呢?这里有两种方法: 现在需要在页面上添加一个下载按钮,点击按钮下载文件. 题外话,这个下载图标是引用的 ...

随机推荐

  1. js中 if不判断解决方式

    $(function() { $("#number").blur(function() { var number = $('#number').val(); var num = $ ...

  2. 二进制部署Kubernetes-v1.14.1集群

    一.部署Kubernetes集群 1.1 Kubernetes介绍 Kubernetes(K8S)是Google开源的容器集群管理系统,K8S在Docker容器技术的基础之上,大大地提高了容器化部署应 ...

  3. xml之基本操作

    XML:Extensible Markup Language(可扩展标记语言)的缩写,是用来定义其它语言的一种元语言,其前身是SGML(Standard Generalized Markup Lang ...

  4. invoke与call

    “调用一个委托实例” 中的 “调用” 对应的是invoke,理解为 “唤出” 更恰当.它和后面的 “在一个对象上调用方法” 中的 “调用” 稍有不同,后则对应的是call.在英语的语境中,invoke ...

  5. Spring boot (12) tomcat jdbc连接池

    默认连接池 tomcat jdbc是从tomcat7开始推出的一个连接池,相比老的dbcp连接池要优秀很多,spring boot将tomcat jdbc作为默认的连接池,只要在pom.xml中引入了 ...

  6. 文件的上传(可以上传照片,word文档,等单个文件)

    jsp: jsp页面: <LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css ...

  7. php基础知识 书写格式

    PHP,是英文超文本预处理语言Hypertext Preprocessor的递归缩写.PHP 是一种 HTML 内嵌式的语言,是一种在服务器端执行的嵌入HTML文档的脚本语言. php嵌入页面的标记有 ...

  8. CXF-JAX-RS开发(一)入门案例

    一.简介 资源驱动.基于HTTP协议[按照标准指定URL,就可以访问数据]以XML|JSON格式传输数据. 二.quickstart 1.创建maven project[Packaging:jar] ...

  9. 【sqli-labs】 less35 GET- Bypass Add Slashes(we dont need them) Integer based (GET型绕过addslashes() 函数的整型注入)

    整型注入不用闭合引号,那就更简单了 http://192.168.136.128/sqli-labs-master/Less-35/?id=0 union select 1,database(),3% ...

  10. POJ_2186_Popular Cows_强连通分量

    Popular Cows Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 30680   Accepted: 12445 De ...