-
C#
中使用
ient
模拟登录博
客园
(GET/POST)
主题
HttpComponents C#
一、
.HttpClient
简介
p>
是微软
.net4.5
中推出的
HTTP
应用程序的编程接口,
微软称
之为
“
现代化的
p>
HTTP
编程接口
”
,
主要提供如下内容:
1.
用户通过
HTTP
使用现代化的
Web
Service
的客户端组件;
2.
能够同时在客户端与服务端同时使用的
HTTP
组件
(比如处理
HTTP
标头和
消息),
为客户端和服务端提供一致的编程模型。
个人看来是抄袭
apache
http client
,目前网上用的人好像不多,
p>
个人认为使
用
httpclient
最大的好处是:不用自己管理
cookie,
只要负责写好请求即可。
由于网上资料不多,这里借登录博客
园网站做个简单的总结其
get
和
po
st
请求
的用法。
< br>查看微软的
api
可以发现其属性方法:
/zh-cn/library/
由其
api
可以看出如果想
设置请求头
只需要在
DefaultRequestHeaders
里进
行设置
创建
httpcliet
可以直接
ne
w HttpClient()
发送请求
< br>可以按发送方式分别调用其方法
,
如
get
调用
GetAsync(Uri) ,
post
调
用
PostAsync(Uri, HttpContent)
,
其它依此类推。。。
二、实例(模
拟
post
登录博客园)
首先,需要说明的是,
本实例环境是
win7
64
位
+vs 2013+ .net
4.5
框架。
1.
< br>使用
vs2013
新建一个控制台程序,或者窗体程序,
如下图所示:
2.
必须引入
框架,否则将不能使用
httpclient
3.
实现代码
<
br>D_VCID_c_login_logincaptcha
的方式,
<
br>在实际过程中发现有些网站登录是 GET
border-box;
border-
box;
string=
border-
box;
string=
border-
box;
string=
border-
box;
string=
using System;
using c;
using
using
using
using
using rExpressions;
using
namespace ClassLibrary1
{
public class Class1
{
private static String dir =
@
///
///
写文件到本地
///
///
///
public static void Write(string
fileName, string html)
{
try
{
FileStream fs = new
FileStream(dir + fileName,
FileMode.C
reate);
StreamWriter sw = new StreamWriter(fs,
t);
(html);
();
();
}catch(Exception ex){
ine(race);
}
}
///
///
写文件到本地
///
///
///
public
static void Write(string fileName, byte[] html)
{
try
{
llBytes(dir + fileName, html);
}
catch (Exception ex)
{
ine(race);
}
}
///
///
登录博客园
///
public static void LoginCnblogs()
{
HttpClient httpClient =
new HttpClient();
ponseContentBufferSize = 256000;
(
la/5.0 (Windows NT 6.1;
WOW64) AppleWebKit/537.36 (KHTML,
like
Gecko) Chrome/36.0.1985.143
Safari/537.36
String url =
HttpResponseMessage response = nc(new
Ur
i(url)).Result;
String
result = StringAsync().Resu
lt;
String username
=
String password =
密码
do
{
String
__EVENTVALIDATION = new
Regex(
ION
String __VIEWSTATE
= new Regex(
String
LBD_VCID_c_login_logincaptcha = new Regex(
ult).Grou
ps[1].Value;
//
图片验证码
url =
ogin_logincaptcha_Capt
chaImage
sult).Groups[1].Value;
response = nc(new Uri(url)).Result;
Write(
().Result);
ine(
输入图片验证码:
String imgCode =
验证码写到本地了,需要手动填写
imgCode = ne();
//
开始登录
url =
List> paramList = new
List>();
(new
KeyValuePair(
(new
KeyValuePair(
(new
KeyValuePair(
E));
(new
KeyValuePair(
NTVALIDATION));
(new KeyValuePair(
(new
KeyValuePair(
(new
KeyValuePair(
tcha
(new KeyVal
uePair(
n_logincaptcha
(new
KeyValuePair(
ode));
(new
KeyValuePair(
登
录
(new
KeyValuePair(
/
response =
ync(new Uri(url), new FormUrl
EncodedCon
tent(paramList)).Result;
result =
StringAsync().Result;
Write(
} while
(ns(
验证码错误,麻烦您重新输入
ine(
登录成功!
//
用完要记得释放
e();
}
public static void Main()
{
LoginCnblogs();
}
}
代码分析:
首先,从
Main
函数开始,调用
L
oginCnblogs
方法;
其次
,使用
GET
方法:
HttpResponseMessage response = nc(new
Ur
i(url)).Result;
String
result = StringAsync().Res
ult;
再者,使用
POST
方法:
List> paramList = new
List>();
(new
KeyValuePair(
RGET
....
response = ync(new
Uri(u
rl), new
FormUrlEncodedContent(paramList)).Result;
result =
StringAsy
nc().Result;
rgb(51, 51, 51); font-family:
Arial,
YaHei
FreeSans,
Arimo,
Sans
micro
hei
Sans
GB
Sans
GB
W3
FontAwesome,
sans-serif;
font-size: 16px;
font-style: normal; font-variant-ligatures:
normal;
font-variant-caps:
normal;
font-weight:
normal;
letter-spacing:
normal;
orphans: 2; text-
align: start; text-indent: 0px; text-transform:
none;
white-space: normal; widows: 2;
word-spacing: 0px;
-webkit-text-stroke-
width: 0px; background-color: rgb(255, 255,
255);
border-
box;
最后,
注意其返回值可以是
string
,
也可以是
byte[],
和
stream
这里
看你需要什么吧。
4.
登录成功后的截图
1).
使用浏览器登录后的截图:
<
/p>
2).
使用
Httpcliet
登录后的截图:
总结,可以发现
C#
中
HttpClient
的用法和
Java
中非常相似,所以,说其抄袭
确实不为过。
========
在
C#
用
HttpWebRequest
中发送
GET/HTTP/HTTPS
请求
这个需求来自于我最近练手的一个项目,在项
目中我需要将一些自己发表的和
收藏整理的网文集中到一个地方存放,如果全部采用手工
操作工作量大而且繁
琐,因此周公决定利用
C#
来实现。在很多地方都需要验证用户身份才可以进行
下一步操作,
这就免不了
POST
请求来登录,
HTTPS
形式的,在
解决过程中遇到了一些小问题,现在跟大家分享。
通用辅助类
下面是我编写的一个辅助类,在这个类中采用了
HttpWebRequest
中发送
GET/HTTP/HTTPS
请求,
因为有的时候需要获取认证信息(如
Cookie
),所以
p>
返回的是
HttpWebResponse
对象,有了返回的
HttpWebResponse
实例,可以
获取登录过程中返回的会话信息,也可以获取响应流。
代码如下:
using System;
using c;
using
using
using ty;
using graphy.X509Certificates;
using ols;
using ty;
using
using
using ssion;
using
rExpressions;
font-family:
YaHei
Sans
GB
Sans
GB
W3
FontAwesome,
sans-serif;
font-size:
16px;
font-style: normal;
font-variant-ligatures: normal; font-variant-caps:
normal; font-weight: normal; letter-
spacing: normal; orphans: 2;
text-
align:
start;
text-indent:
0px;
text-transform:
none;
white-space:
normal; widows: 2; word-spacing: 0px;
-webkit-text-stroke-width: 0px;
background-color: rgb(255, 255,
255);
namespace BaiduCang
{
///
///
有关
HTTP
请求的辅助类<
/p>
///
public class HttpWebResponseUtility
{
private static readonly
string DefaultUserAgent =
.NET CLR 1.1.4322; .NET CLR 2.0.50727)
///
///
创建
方式的
HTTP
请求
///
///
请求的
URL
///
请求的超时时间
///
请求的客户端浏览器信息,可以为空
///
随同
HTTP
请求发送的
Cookie
信息,
如果不需要身份验证可以
为空
///
public
static HttpWebResponse
CreateGetHttpRespon
se(string url,int?
timeout, string
userAgent,CookieCollec
tion cookies)
{
if
(OrEmpty(url))
{
throw new
ArgumentNullException(
}
HttpWebRequest request =
(ur
l) as HttpWebRequest;
=
ent = DefaultUserAgent;
if (!OrEmpty(userAgent))
{
ent = userAgent;
}
if (ue)
{
t =
}
if (cookies != null)
{
Container = new CookieConta
iner();
(cookies);
}
return ponse() as HttpWebRespon
se;
}
///
///
创建
POS
T
方式的
HTTP
请求
///
///
请求的
URL
///
随同请求
POST
的参数名称及
参数值字典
///
请求的超时时间
///
请求的客户端浏览器信息,可以为空
///
发送
HTTP
请求时所用的编码
///
随同
HTTP
请求发送的
Cookie
信息,
如果不需要身份验证可以
为空
///
public static HttpWebResponse
CreatePostHttpRespo
nse(string
url,IDictionary parameters,int? timeout,
strin
g userAgent,Encoding
requestEncoding,CookieCollection
coo
kies)
-
-
-
-
-
-
-
-
-
上一篇:MSP430F5418使用总结
下一篇:SQL SERVER安装问题集锦