这段时间明显疲惫,从来文字描述当中就可以感觉出来有点匆匆交货的感觉。
没法,中国的软件业整个行业都是这样的亚健康地发展地,要生存实属不易。
好了,发完两句牢骚之后继续主题,linkedin开发
在上LinkedIn应用开发系列(三)中,已经可以对request token的爬网授权了,而得到的两个参数oauth_token和oauth_verifier在这一节中可以用到了。而接下来这一文当中,要做的就是通过授权后的request token再获取权限操作的access token。
获取access token我们是通过 https://api.linkedin.com/uas/oauth/accessToken这个链接去获取的
而获取过程跟LinkedIn应用开发系列(二) ---- 获取Request token 一文中的参数基本相同,只是多了两个两个参数oauth_token和oauth_verifier的数据,这里就不在重复了。
好了,去除重复的代码,只要加上两上处理的方法就可以了。比较简单
{
string rquestUrl = string .Empty;
string query = string .Empty;
string response = string .Empty;
string nonce = this .Nonce;
string timeStamp = this .TimeStamp;
Uri uri = new Uri(url);
string sign = GenSign(uri, this .ApiKey, this .Secret, Token, TokenSecret, " POST " , CallBackUrl, timeStamp, nonce, out rquestUrl, out query);
response = WebRequest(method, rquestUrl);
return response;
}
public string GetAccessToken()
{
if ( string .IsNullOrEmpty(Token) || string .IsNullOrEmpty(Verifier))
throw new Exception( " The request token and verifier can not empty " );
string response = AuthWebRequest( " POST " , AccessUrl);
if (response.Length > 0 )
{
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs[ " oauth_token " ] != null )
{
this .Token = qs[ " oauth_token " ];
}
if (qs[ " oauth_token_secret " ] != null )
{
this .TokenSecret = qs[ " oauth_token_secret " ];
}
}
return Token;
}
这样,我们能过开发linkedin开发系统列的二,三,四三步。我们就可以得到操作的access token了,当接收到这个token之后,我们就可以对linkedin的http的API的各种操作进行了。
代码比较乱,所以我重新整理一下了,变成操作的两个类。整理过,代码依然比较乱(谅解:这测试版本的代码)
using System.Collections.Generic;
using System.Linq;
using System.Web;
///
/// AppSetting
///
///
[Serializable]
public class AppSetting
{
const string _defaultapiKey = "" ;
const string _defaultSecret = "" ;
public const string unreservedChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~ " ;
static string _apiKey = System.Configuration.ConfigurationManager.AppSettings.Get( " ApiKey " );
static string _secret = System.Configuration.ConfigurationManager.AppSettings.Get( " Secret " );
public string ApiKey
{
get
{
return string .IsNullOrEmpty(_apiKey) ? _defaultapiKey : _apiKey;
}
set
{
_apiKey = value;
}
}
public string Secret
{
get
{
return string .IsNullOrEmpty(_secret) ? _defaultSecret : _secret;
}
set
{
_secret = value;
}
}
public string RequestTokenUrl
{
get
{
return System.Configuration.ConfigurationManager.AppSettings.Get( " RequestUrl " );
}
}
public string AuthorizeUrl
{
get
{
return System.Configuration.ConfigurationManager.AppSettings.Get( " AuthorizeUrl " );
}
}
public string AccessUrl
{
get
{
return System.Configuration.ConfigurationManager.AppSettings.Get( " AccessUrl " );
}
}
public string CallBackUrl
{
get
{
return System.Configuration.ConfigurationManager.AppSettings.Get( " CallBackUrl " );
}
}
public string OauthUrl
{
get
{
return System.Configuration.ConfigurationManager.AppSettings.Get( " OauthUrl " );
}
}
public string Nonce
{
get
{
return ( new Random()).Next( 123400 , 9999999 ).ToString();
}
}
public string TimeStamp
{
get
{
TimeSpan ts = DateTime.UtcNow - new DateTime( 1970 , 1 , 1 , 0 , 0 , 0 , 0 );
string timeStamp = Convert.ToInt64(ts.TotalSeconds).ToString();
return timeStamp;
}
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Security.Cryptography;
///
/// LinkedInBase 的摘要说明
///
public class LinkedInBase : AppSetting
{
public string Verifier = string .Empty;
public string Token = string .Empty;
public string TokenSecret = string .Empty;
public string Email { get ; set ; }
public string Pwd { get ; set ; }
public LinkedInBase( string email, string pwd)
{
this .Email = email;
this .Pwd = pwd;
}
public LinkedInBase() { }
string UrlEncode( string value)
{
StringBuilder sb = new StringBuilder();
foreach ( char a in value)
{
if (unreservedChars.IndexOf(a) != - 1 )
{
sb.Append(a);
}
else
{
sb.Append( ' % ' + String.Format( " {0:X2} " , ( int )a));
}
}
return sb.ToString();
}
string GenSignString(Uri url, string key, string token, string tokenSecret, string method, string callback, string timeStamp, string nonce, out string requestUrl, out string parameters)
{
requestUrl = string .Format( " {0}://{1}{2} " , url.Scheme, url.Host, url.AbsolutePath);
StringBuilder sb = new StringBuilder();
string requestparameters = @" oauth_callback={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={3}&oauth_version=1.0 " ;
sb.AppendFormat(requestparameters, UrlEncode(callback), key, nonce, timeStamp);
parameters = sb.ToString();
sb = new StringBuilder();
sb.AppendFormat( " {0}& " , method.ToUpper());
sb.AppendFormat( " {0}& " , UrlEncode(requestUrl));
sb.AppendFormat( " {0} " , UrlEncode(parameters));
return sb.ToString();
}
string GenSign(Uri url, string _key, string _secret, string token, string tokenSecret, string method, string callback, string timeStamp, string nonce, out string requestUrl, out string parameters)
{
string sigstring = GenSignString(url, _key, token, tokenSecret, method, callback, timeStamp, nonce, out requestUrl, out parameters);
HMACSHA1 ha = new HMACSHA1();
ha.Key = Encoding.ASCII.GetBytes( string .Format( " {0}&{1} " , UrlEncode(_secret), string .IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
byte [] _buffer = System.Text.Encoding.ASCII.GetBytes(sigstring);
byte [] _bytes = ha.ComputeHash(_buffer);
string sig = Convert.ToBase64String(_bytes);
parameters = parameters + " &oauth_signature= " + HttpUtility.UrlEncode(sig);
return sig;
}
string WebRequest( string method, string url)
{
return WebRequest(method, url, string .Empty);
}
string WebRequest( string method, string url, string postData)
{
HttpWebRequest webRequest = null ;
StreamWriter requestWriter = null ;
string response = string .Empty;
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method;
webRequest.ServicePoint.Expect100Continue = false ;
webRequest.Timeout = 10000 ;
if (method.ToUpper() == " POST " )
{
webRequest.ContentType = " application/x-www-form-urlencoded " ;
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw ;
}
finally
{
requestWriter.Close();
requestWriter = null ;
}
}
StreamReader responseReader = null ;
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
response = responseReader.ReadToEnd();
}
catch (Exception e)
{
throw e;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null ;
}
return response;
}
string GenPostData( string email, string pwd, string token, string csrfToken)
{
string s = string .Format( @" email={0}&password={1}&duration=0&extra=&access=-3&agree=true&oauth_token={2}&appId={3}&csrfToken={4}&sourceAlias=uas-oauth-authorize " ,
email, pwd, token, string .Empty, csrfToken);
return s;
}
string LoginSpider()
{
CookieCollection collection = null ;
HttpWebRequest cookie_request = (HttpWebRequest)System.Net.WebRequest.Create(AuthorizeUrl + " ?oauth_token= " + Token);
CookieContainer container = new CookieContainer();
cookie_request.Method = " GET " ;
cookie_request.ContentType = " application/x-www-form-urlencoded " ;
cookie_request.KeepAlive = true ;
cookie_request.CookieContainer = container;
HttpWebResponse cookie_response = (HttpWebResponse)cookie_request.GetResponse();
collection = cookie_response.Cookies;
string postData = GenPostData(Email, Pwd, this .Token, collection[ " JSESSIONID " ].Value.Replace( " \ "" , string.Empty));
ASCIIEncoding encoding = new ASCIIEncoding();
byte [] data = encoding.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(OauthUrl);
request.Method = " Post " ;
request.ContentType = " application/x-www-form-urlencoded " ;
request.ContentLength = data.Length;
request.KeepAlive = true ;
request.CookieContainer = container;
request.CookieContainer.Add(collection);
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0 , data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = collection;
if (response.StatusCode == HttpStatusCode.OK)
{
NameValueCollection qs = HttpUtility.ParseQueryString(response.ResponseUri.Query);
if (qs[ " oauth_token " ] != null )
{
this .Token = qs[ " oauth_token " ];
}
if (qs[ " oauth_verifier " ] != null )
{
this .Verifier = qs[ " oauth_verifier " ];
}
// StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
// string content = reader.ReadToEnd();
}
if ( ! string .IsNullOrEmpty(Verifier))
return Token;
return string .Empty;
}
public string GetRequestToken()
{
string rquestUrl = string .Empty;
string query = string .Empty;
string nonce = this .Nonce;
string timeStamp = this .TimeStamp;
Uri uri = new Uri(RequestTokenUrl);
GenSign(uri, this .ApiKey, this .Secret, string .Empty, string .Empty, " POST " , CallBackUrl, timeStamp, nonce, out rquestUrl, out query);
string response = WebRequest( " POST " , rquestUrl, query);
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs[ " oauth_token " ] != null )
{
Token = qs[ " oauth_token " ];
}
if (qs[ " oauth_token_secret " ] != null )
{
TokenSecret = qs[ " oauth_token_secret " ];
}
return Token;
}
public string AuthorizeToken()
{
if ( string .IsNullOrEmpty(Token))
throw new Exception( " Request token is empty " );
return LoginSpider();
}
string AuthWebRequest( string method, string url)
{
string rquestUrl = string .Empty;
string query = string .Empty;
string response = string .Empty;
string nonce = this .Nonce;
string timeStamp = this .TimeStamp;
Uri uri = new Uri(url);
string sign = GenSign(uri, this .ApiKey, this .Secret, Token, TokenSecret, " POST " , CallBackUrl, timeStamp, nonce, out rquestUrl, out query);
response = WebRequest(method, rquestUrl);
return response;
}
public string GetAccessToken()
{
if ( string .IsNullOrEmpty(Token) || string .IsNullOrEmpty(Verifier))
throw new Exception( " The request token and verifier can not empty " );
string response = AuthWebRequest( " POST " , AccessUrl);
if (response.Length > 0 )
{
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs[ " oauth_token " ] != null )
{
this .Token = qs[ " oauth_token " ];
}
if (qs[ " oauth_token_secret " ] != null )
{
this .TokenSecret = qs[ " oauth_token_secret " ];
}
}
return Token;
}
public string WebRequestAPI( string method, string url, string postData)
{
string rquestUrl = string .Empty;
string query = string .Empty;
string response = string .Empty;
string nonce = this .Nonce;
string timeStamp = this .TimeStamp;
Uri uri = new Uri(url);
string sign = GenSign(uri, this .ApiKey, this .Secret, Token, TokenSecret, " POST " , CallBackUrl, timeStamp, nonce, out rquestUrl, out query);
HttpWebRequest webRequest = null ;
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method;
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.AllowWriteStreamBuffering = true ;
webRequest.PreAuthenticate = true ;
webRequest.ServicePoint.Expect100Continue = false ;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
webRequest.Headers.Add( " Authorization " , " OAuth realm=\ " http: // api.linkedin.com/\",oauth_consumer_key=\"" + this.ApiKey + "\",oauth_token=\"" + this.Token + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_signature=\"" + HttpUtility.UrlEncode(sign) + "\",oauth_timestamp=\"" + timeStamp + "\",oauth_nonce=\"" + nonce + "\",oauth_verifier=\"" + this.Verifier + "\", oauth_version=\"1.0\"");
if (postData != null )
{
byte [] fileToSend = Encoding.UTF8.GetBytes(postData);
webRequest.ContentLength = fileToSend.Length;
Stream reqStream = webRequest.GetRequestStream();
reqStream.Write(fileToSend, 0 , fileToSend.Length);
reqStream.Close();
}
StreamReader responseReader = null ;
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
response = responseReader.ReadToEnd();
}
catch (Exception e)
{
throw e;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null ;
}
return response;
}
}
而调用的时候,直接调用以下三个方法就可以了
LinkedInBase _oauth = new LinkedInBase("your linkedin access", "password");
String requestToken = _oauth.GetRequestToken();
_oauth.AuthorizeToken();
string acctoken = _oauth.GetAccessToken();
而接下来的开发,只要调用WebRequestAPI就可以完成各种操作了