[C#]新浪微博获取AccessToken以及接口的调用
首先,页面中放一个WebBrowser控件,页面加载完毕后进入OAuth授权页面
void AuthorWindow_Loaded(object sender, RoutedEventArgs e) { Uri uri = new Uri("https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=https://api.weibo.com/oauth2/default.html //这里redirect_uri以https://api.weibo.com/oauth2/default.html为例
"); webbrowser.Navigate(uri); }
当授权完成后页面会跳转到
https://api.weibo.com/oauth2/default.html?code=xxxxxxxxxxxxxxxxxxxxx
我们需要在 webbrowser.Navigating 事件中拦截这个code
webbrowser.Navigating += webbrowser_Navigating;
void webbrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e) { Uri uri = e.Uri; if (uri.AbsoluteUri.StartsWith("https://api.weibo.com/oauth2/default.html")) { string code=uri.AbsoluteUri.Substring(uri.AbsoluteUri.IndexOf("code=")+5); e.Cancel = true; if (code == "21330") { MessageBox.Show("授权失败"); } else { //成功拦截到code,注意把code存起来 } } }
下一步以code获取AccessToken,注意这一步必须以POST方式提交,而且参数都加在url后面,不需要对Stream进行写操作
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT-SECRECT&grant_type=authorization_code&redirect_uri=https://api.weibo.com/oauth2/default.html&code="+code);//code为上一步得到的code httpRequest.Method = "POST"; httpRequest.Headers["Pragma"] = "no-cache"; httpRequest.Headers["Cache-Control"] = "no-cache"; httpRequest.ContentType = "Content-Type:application/x-www-form-urlencoded; charset=UTF-8"; httpRequest.BeginGetResponse(r => { HttpWebResponse httpResponse = null; try { httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r); using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream(), System.Text.UTF8Encoding.UTF8)) { string xmStream = reader.ReadToEnd(); reader.Close(); //放回json if (xmStream.Contains("access_token")) { int start=xmStream.IndexOf("token")+8; int end=xmStream.IndexOf("remind")-3; access_token = xmStream.Substring(start, end-start); } else { } } } catch (Exception) { // MessageBox.Show("(~.~)失败了"); } finally { if (httpRequest != null) httpRequest.Abort(); if (httpResponse != null) httpResponse.Close(); } }, httpRequest);
到这里,就获取到accesstoken了,就可以调用相关接口了
有一点必须注意,所有需要POST的接口都是以“uri+参数”这种方式提交,不需要写流操作