2018-8-10-win10-uwp-httpClient-登陆CSDN
title | author | date | CreateTime | categories |
---|---|---|---|---|
win10 uwp httpClient 登陆CSDN
|
lindexi
|
2018-08-10 19:16:53 +0800
|
2018-2-13 17:23:3 +0800
|
Win10 UWP
|
本文告诉大家如何模拟登陆csdn,这个方法可以用于模拟登陆其他网站。
HttpClient 使用 Cookie
我们可以使用下面代码让 HttpClient 使用 Cookie ,有了这个才可以保存登陆,不然登陆成功下次访问网页还是没登陆。
CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient http = new HttpClient(handler);
虽然已经有Cookie
,但是还缺少一些请求需要带的头,因为浏览器是会告诉网站,需要的Accept
,为了假装这是一个浏览器,所以就需要添加Accept
和Accept-Encoding
Accept-Language
User-Agent
添加 Accept
下面的代码可以添加Accept
,这里后面的字符串可以自己使用浏览器查看,复制。
http.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
添加 Accept-Encoding
http.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
如果有 gzip
就需要解压,这个现在不太好弄,建议不要加。
添加 Accept-Language
http.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language", "zh-CN,zh;q=0.8");
添加 User-Agent
http.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
更多User-Agent
请看win10 uwp 如何让WebView标识win10手机
ContentType
如果设置 ContentType 需要在发送的内容进行添加
content = new StringContent("{\"loginName\":\"lindexi\",\"password\":\"csdn\",\"autoLogin\":false}")
{
Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
};
发送数据
如果需要使用 Post 或 get 发送数据,那么可以使用HttpContent
做出数据,提供的类型有StringContent
、FormUrlEncodedContent
等。
其中StringContent
最简单,而FormUrlEncodedContent
可以自动转换。
str = $"username={account.UserName}&password={account.Key}<={lt}&execution={execution}&_eventId=submit";
str = str.Replace("@", "%40"); HttpContent content = new StringContent(str, Encoding.UTF8);
上面代码就是使用 StringContent
可以看到需要自己转换特殊字符,当然一个好的方法是使用 urlencoding 转换。
如果使用FormUrlEncodedContent
就不需要做转换
content=new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("username",account.UserName),
new KeyValuePair<string, string>("password",account.Key),
new KeyValuePair<string, string>("lt",lt),
new KeyValuePair<string, string>("execution",execution),
new KeyValuePair<string, string>("_eventId","submit")
});
如果需要上传文件,那么需要使用MultipartFormDataContent
content = new MultipartFormDataContent();
((MultipartFormDataContent)content).Headers.Add("name", "file1"); ((MultipartFormDataContent)content).Headers.Add("filename", "20170114120751.png");
var stream = new StreamContent(await File.OpenStreamForReadAsync());
((MultipartFormDataContent)content).Add(stream);
登陆方法
打开 https://passport.csdn.net/account/login 可以看到这个界面
右击查看源代码,可以拿到上传需要使用的两个变量 lt 和 execution
在登陆的时候,使用 post 把账号密码、lt execution 上传就可以登陆
模拟登陆csdn
于是下面就是模拟登陆
获得账号信息
AccountCimage account = AppId.AccoutCimage;
cookie
CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient http = new HttpClient(handler);
获得登陆需要的流水号
var url = new Uri("https://passport.csdn.net/account/login"); http.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//http.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
http.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language", "zh-CN,zh;q=0.8");
http.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"); handler.UseCookies = true;
handler.AllowAutoRedirect = true; string str = await http.GetStringAsync(url);
Regex regex = new Regex(" type=\"hidden\" name=\"lt\" value=\"([\\w|\\-]+)\"");
var lt = regex.Match(str).Groups[1].Value;
regex = new Regex("type=\"hidden\" name=\"execution\" value=\"(\\w+)\"");
var execution = regex.Match(str).Groups[1].Value;
登陆
str = $"username={account.UserName}&password={account.Key}<={lt}&execution={execution}&_eventId=submit";
str = str.Replace("@", "%40"); HttpContent content = new StringContent(str, Encoding.UTF8); str = await content.ReadAsStringAsync();
content=new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("username",account.UserName),//.Replace("@", "%40")),
new KeyValuePair<string, string>("password",account.Key),
new KeyValuePair<string, string>("lt",lt),
new KeyValuePair<string, string>("execution",execution),
new KeyValuePair<string, string>("_eventId","submit")
});
str = await content.ReadAsStringAsync(); str = await (await http.PostAsync(url, content)).Content.ReadAsStringAsync();
查看登陆
url = new Uri("http://write.blog.csdn.net/");
str = await http.GetStringAsync(url);上传文件
content = new MultipartFormDataContent();
((MultipartFormDataContent)content).Headers.Add("name", "file1"); ((MultipartFormDataContent)content).Headers.Add("filename", "20170114120751.png");
var stream = new StreamContent(await File.OpenStreamForReadAsync());
((MultipartFormDataContent)content).Add(stream);
str = await ((MultipartFormDataContent)content).ReadAsStringAsync();
url = new Uri("http://write.blog.csdn.net/article/UploadImgMarkdown?parenthost=write.blog.csdn.net");
var message = await http.PostAsync(url, content);
if (message.StatusCode == HttpStatusCode.OK)
{
ResponseImage(message);
} private async void ResponseImage(HttpResponseMessage message)
{
using (MemoryStream memoryStream = new MemoryStream())
{
int length = 1024;
byte[] buffer = new byte[length];
using (GZipStream zip = new GZipStream(await message.Content.ReadAsStreamAsync(), CompressionLevel.Optimal))
{
int n;
while ((n = zip.Read(buffer, 0, length)) > 0)
{
memoryStream.Write(buffer, 0, n);
}
} using (StreamReader stream = new StreamReader(memoryStream))
{
string str = stream.ReadToEnd();
}
}
}
使用 WebView 模拟登陆 csdn
下面给大家一个叫简单方法模拟登陆csdn
GeekWebView.Navigate(new Uri("http://passport.csdn.net/")); GeekWebView.NavigationCompleted += OnNavigationCompleted; F = async () =>
{ var functionString = string.Format(@"document.getElementsByName('username')[0].value='{0}';", "lindexi_gd@163.com");
await GeekWebView.InvokeScriptAsync("eval", new string[] { functionString });
functionString = string.Format(@"document.getElementsByName('password')[0].value='{0}';", "密码");
await GeekWebView.InvokeScriptAsync("eval", new string[] { functionString }); functionString = string.Format(@"document.getElementsByClassName('logging')[0].click();");
await GeekWebView.InvokeScriptAsync("eval", new string[] { functionString });
}; private Action F { set; get; } private void OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
F();
}
当然,这时需要修改登陆信息,我上面写的是我的。如果遇到有验证码,那么这个方法是不可使用,因为输入验证码暂时还没法做。
最新文章
- .NET WEB程序员需要掌握的技能
- JavaScript学习笔记-函数实例
- docker不稳定 short running containers with -rm failed to destroy
- [codeforces 293]A. Weird Game
- H264关于RTP协议的实现
- 【RoR win32】新rails运行后0.0.0.0:3000不能访问
- AndroidManifest.xml清单文件要点
- 【翻译习作】 Windows Workflow Foundation程序开发-第一章05
- 向Array中添加改进的冒泡排序
- poi对wps excel的支持
- Linux I2C设备驱动编写(二)
- Automated Telephone Exchange
- nginx 禁止非指定域名访问
- phantomjs 爬去动态页面
- 操作系统:修改VirtualBox for Mac的虚拟硬盘大小
- day33 锁和队列
- LwIP Application Developers Manual5---高层协议之DHCP,AUTOIP,SNMP,PPP
- java基础 (三)之ConcurrentHashMap(转)
- Wepy在VScode中的高亮显示
- API(二)之Requests and Responses
热门文章
- Codecraft-17 and Codeforces Round #391 - A
- python关于window文件写入后,换行默认\r\n的问题
- golang中最大协程数的限制(线程)
- 51nod 1490: 多重游戏(树上博弈)
- mobx学习笔记03——mobx基础语法(decorator修饰器)
- 线性规划(Simplex单纯形)与对偶问题
- flutter Container组件和Text组件
- signer information does not match signer information of other classes in the same package
- [CSP-S模拟测试]:v(hash表+期望DP)
- 重写ArcGIS的TiledMapServiceLayer调用天地图瓦片