编程点滴

FOR WEB WINFORM DEVELOP!!

导航

GoogleReader用户登陆验证C#具体实现

Posted on 2011-02-21 10:46  grayboy  阅读(3422)  评论(6编辑  收藏  举报

继前两篇文章

google reader api:http://www.cnblogs.com/mybear/archive/2011/02/18/1957704.html

GoogleReader用户登陆验证原理:http://www.cnblogs.com/mybear/archive/2011/02/18/1957769.html

相信大家对GoogleReader api已经有所认识,下面就讲下GoogleReader用户登陆验证C#具体实现

1.创建HttpWebRequest

private HttpWebRequest CreateRequest(string url)
{
HttpWebRequest webRequest
= WebRequest.Create(url) as HttpWebRequest;
IWebProxy defaultParoxy
= HttpWebRequest.GetSystemWebProxy();
webRequest.Proxy
= defaultParoxy;
webRequest.UserAgent
= "GoogleReader for Windows/"+Assembly.GetExecutingAssembly().GetName().Version;
webRequest.CookieContainer
= _CookieContainer;
webRequest.ServicePoint.Expect100Continue
= false;
webRequest.Timeout
= 20000;

if (_isLoginIn)
webRequest.Headers.Add(
"Authorization", "GoogleLogin auth=" + _LoginAuth[2].Split('=')[1]);
return webRequest;
}

2.使用HttpPost传递登陆参数

private string PostGoogleLogin(HttpWebRequest webRequest,string queryString)
{
string ResponseString = string.Empty;
webRequest.ContentType
= "application/x-www-form-urlencoded";
webRequest.Method
= "POST";

byte[] QueryData = Encoding.UTF8.GetBytes(queryString);
webRequest.ContentLength
= QueryData.Length;
try
{
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(QueryData,
0, QueryData.Length);
stream.Close();
ResponseString
= GetResponseString(webRequest);
}
}
catch (Exception ex)
{
LoginError
+= ex.ToString() + "\r\n";
}
return ResponseString;
}

3.传递用户名和密码实现登陆

public void GoogleLogin(string email,string password)
{
string SID_ID = string.Empty;
string responseData = string.Empty;
List
<Parameter> queryParams = new List<Parameter>();
queryParams.Add(
new Parameter("service", "reader"));
queryParams.Add(
new Parameter("Email", Uri.EscapeDataString(email)));
queryParams.Add(
new Parameter("Passwd", Uri.EscapeDataString(password)));
queryParams.Add(
new Parameter("source", "Mobile Newspaper/0.1"));
queryParams.Add(
new Parameter("continue", "http://www.google.com"));

HttpWebRequest webRequest
=CreateRequest("https://www.google.com/accounts/ClientLogin");

responseData
= PostGoogleLogin(webRequest, HttpUtil.GetQueryParamters(queryParams));
string pattern="SID=(.*)";
Regex reg
= new Regex(pattern, RegexOptions.IgnoreCase);
if (reg.IsMatch(responseData))
{
_isLoginIn
= true;
_LoginAuth
= responseData.Split('\n');
SID_ID
= reg.Match(responseData).Groups[1].Value;
_CookieContainer.Add(
new Cookie("SID",SID_ID,"/",".google.com"));
}
}

至此,google用户登陆验证完成了!我们可以根据googlereader提供的API打造一个属于自己的客户端RSS订阅器!

比如,我们要获得已阅读的20篇文章:可以用httpget的方法访问:http://www.google.com/reader/atom/user/[user ID]/state/com.google/read

[user ID]可以使用“-”来代表当前登陆的用户,返回的记录是XML数据格式: