oAuth2.0 登录新浪微博 发送新浪微博 代码

  1 public class SinaoAuth
  2     {
  3         string APIHost = "";
  4         public SinaoAuth() 
  5         {
  6             APIHost = SinaConfig.Sina_Host;
  7         }
  8 
  9         #region 绑定微博帐号
 10         /// <summary>
 11         /// 绑定微博帐号
 12         /// </summary>
 13         /// <param name="username">新浪微博的登录帐号</param>
 14         /// <param name="password">新浪微博的登录密码</param>
 15         /// <returns>失败返回null</returns>
 16         public string Binding(String username, String password)
 17         {
 18             if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
 19             {
 20                 return null;
 21             }
 22             string apiUrl = "https://api.weibo.com/oauth2/access_token?client_id=" + SinaConfig.Sina_AppKey + "&client_secret=" + SinaConfig.Sina_AppSecurity + "&grant_type=password&username=" + username + "&password=" + password;
 23 
 24             try
 25             {
 26                 HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(apiUrl);
 27                 webReq.Method = "POST";
 28                 webReq.Timeout = 2000;
 29                 //webReq.Headers.Add("Authorization", header);
 30                 HttpWebResponse webRsp = (HttpWebResponse)webReq.GetResponse();
 31 
 32                 using (StreamReader reader = new StreamReader(webRsp.GetResponseStream()))
 33                 {
 34                     string rsp = reader.ReadToEnd();
 35                     AccessTokenResponse accessToken = new AccessTokenResponse(rsp);
 36                     if (accessToken != null && accessToken.IsValid)
 37                     {
 38                         return accessToken.AccessToken;
 39                     }
 40                     else
 41                     {
 42                         return null;
 43                     }
 44                 }
 45             }
 46             catch (WebException e)
 47             {
 48                 return GetErrorMessage(e);
 49             }
 50         }
 51 
 52         private string GetErrorMessage(WebException e) 
 53         {
 54             try
 55             {
 56                 HttpWebResponse webResponse = e.Response as HttpWebResponse;
 57                 StreamReader myread = new StreamReader(webResponse.GetResponseStream());
 58                 string error = myread.ReadToEnd();
 59                 ErrorMessage errorMessage = new ErrorMessage(error);
 60                 return errorMessage.Error_code;
 61             }
 62             catch (Exception ex)
 63             {
 64                 return ex.Message;
 65                 throw;
 66             }
 67         }
 68 
 69         /// <summary>
 70         /// 用web方式登录
 71         /// </summary>
 72         /// <param name="code"></param>
 73         /// <returns></returns>
 74         public string Binding(string code)
 75         {
 76             string apiUrl = "https://api.weibo.com/oauth2/access_token?client_id="+SinaConfig.Sina_AppKey+"&client_secret="+
 77                 SinaConfig.Sina_AppSecurity + "&grant_type=authorization_code&redirect_uri=http://sae.sina.com.cn/&code="+code;
 78             try
 79             {
 80                 HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(apiUrl);
 81                 webReq.Method = "POST";
 82                 webReq.Timeout = 2000;
 83                 //webReq.Headers.Add("Authorization", header);
 84                 HttpWebResponse webRsp = (HttpWebResponse)webReq.GetResponse();
 85 
 86                 using (StreamReader reader = new StreamReader(webRsp.GetResponseStream()))
 87                 {
 88                     string rsp = reader.ReadToEnd();
 89                     AccessTokenResponse accessToken = new AccessTokenResponse(rsp);
 90                     if (accessToken != null && accessToken.IsValid)
 91                     {
 92                         return accessToken.AccessToken;
 93                     }
 94                     else
 95                     {
 96                         return null;
 97                     }
 98                 }
 99             }
100             catch (WebException e)
101             {
102                 return GetErrorMessage(e);
103             }
104         }
105 
106         /// <summary>
107         /// 直接发送微博
108         /// </summary>
109         /// <param name="access_token"></param>
110         /// <param name="status"></param>
111         /// <returns></returns>
112         public string update(string access_token,string status) 
113         {
114             string apiUrl = "https://api.weibo.com/2/statuses/update.json";
115             try
116             {
117                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(apiUrl);
118                 request.Method = "POST";
119                 request.Timeout = 2000;               
120                 request.ContentType = "application/x-www-form-urlencoded";
121                 System.Text.Encoding encoding = System.Text.Encoding.ASCII;
122                 byte[] bytesToPost = encoding.GetBytes("access_token=" + access_token + "&status=" + UrlEncode(status));
123                 request.ContentLength = bytesToPost.Length;
124                 System.IO.Stream requestStream = request.GetRequestStream();
125                 requestStream.Write(bytesToPost, 0, bytesToPost.Length);
126                 requestStream.Close();
127 
128                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
129                 using (StreamReader reader = new StreamReader(response.GetResponseStream()))
130                 {
131                     string rsp = reader.ReadToEnd();
132                     if (rsp != "")
133                     {
134                         return "SUCCESS";
135                     }
136                 }
137                 return null;
138             }
139             catch (WebException ex)
140             {
141                 return GetErrorMessage(ex);
142             }
143         }
144 
145         public static string UrlEncode(string str)
146         {
147             StringBuilder sb = new StringBuilder();
148             byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
149             for (int i = 0; i < byStr.Length; i++)
150             {
151                 sb.Append(@"%" + Convert.ToString(byStr[i], 16));
152             }
153 
154             return (sb.ToString());
155         }
156 
157         /// <summary>
158         /// 发送带图片的微博
159         /// </summary>
160         /// <param name="access_token"></param>
161         /// <param name="status">文字内容</param>
162         /// <param name="pic">图片的byte流</param>
163         /// <returns></returns>
164         public string ShareImg(string access_token,string status,byte[] pic) 
165         {
166             string apiUrl = "https://api.weibo.com/2/statuses/upload.json?access_token=" + access_token + "&status=" +UrlEncode(status) + "&pic=" + @pic + "";
167             
168             try
169             {
170                 HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(apiUrl);
171                 webReq.Method = "POST";
172                 webReq.Timeout = 2000; 
173                 string boundary = Guid.NewGuid().ToString();
174                 //webReq.ContentType = string.Format("text/html; charset=GBK");
175                 webReq.ContentType=string.Format("multipart/form-data; boundary={0}", boundary);
176                 byte[] contents = getMultipartContent(status, pic, boundary);
177                 webReq.ContentLength = contents.Length;
178                 webReq.GetRequestStream().Write(contents, 0, contents.Length);
179 
180                 HttpWebResponse webRsp = (HttpWebResponse)webReq.GetResponse();
181 
182                 using (StreamReader reader = new StreamReader(webRsp.GetResponseStream()))
183                 {
184                     string rsp = reader.ReadToEnd();
185                     if (rsp != "")
186                     {
187                         return "SUCCESS";
188                     }
189                 }
190                 return null;
191             }
192             catch (WebException e)
193             {
194                 return GetErrorMessage(e);
195             }
196         }
197 
198 
199         private byte[] getMultipartContent(string msg, byte[] pic, string boundary)
200         {
201             string contentEncoding = "iso-8859-1";
202             string header = string.Format("--{0}", boundary);
203             string footer = string.Format("--{0}--", boundary);
204 
205             StringBuilder contents = new StringBuilder();
206             contents.AppendLine(header);
207             contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "status"));
208             contents.AppendLine("Content-Type: text/plain;  charset=US-ASCII");
209             contents.AppendLine("Content-Transfer-Encoding: 8bit");
210             contents.AppendLine();
211             contents.AppendLine(UrlEncode(msg));
212 
213             contents.AppendLine(header);
214             contents.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", "source"));
215             contents.AppendLine("Content-Type: text/plain;  charset=US-ASCII");
216             contents.AppendLine("Content-Transfer-Encoding: 8bit");
217             contents.AppendLine();
218             contents.AppendLine(SinaConfig.Sina_AppKey);
219 
220             contents.AppendLine(header);
221             string fileHeader = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", "pic", "");
222             string fileData = System.Text.Encoding.GetEncoding(contentEncoding).GetString(pic);
223 
224             contents.AppendLine(fileHeader);
225             contents.AppendLine("Content-Type: application/octet-stream; charset=UTF-8");
226             contents.AppendLine("Content-Transfer-Encoding: binary");
227             contents.AppendLine();
228             contents.AppendLine(fileData);
229             contents.AppendLine(footer);
230 
231             return Encoding.GetEncoding(contentEncoding).GetBytes(contents.ToString());
232         }
233 
234         #endregion
235     }

提供学习交流,不正确的希望园子们指出来 谢谢 哈。

posted @ 2012-04-11 14:57  行者,无疆  阅读(2722)  评论(7编辑  收藏  举报