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     }

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

转载于:https://www.cnblogs.com/Lovetuya/archive/2012/04/11/2442366.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/262804.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

下载 sdk struts java

<action name"sdkDownload" class"com.curiousby.sdkDownload"><!-- result的Type必须为stream --><result name"success" type"stream"><param name"contentType">application/octet-stream;char…

微信小程序省市区联动,自定义地区字典

最近在做一个项目的时候遇到了这么一个问题&#xff0c;就是省市区的联动呢&#xff0c;我们需要自定义字典来设置&#xff0c;那么微信小程序自带的省市区选择就不能用了&#xff0c;经过三根烟的催化&#xff0c;终于写出来了。下面献上代码示例。 首先是在utils文件夹存入ar…

论文翻译《Object-Level Ranking: Bringing Order to Web Objects》

Object-Level Ranking: Bringing Order to Web Objects Zaiqing Nie Yuanzhi Zhang Jirong Wen Weiying Ma 摘要&#xff1a; 现在的网络搜索方法实际上是做文档级排名和检索&#xff0c;与之相对比&#xff0c;我们在探索一种新的聚合体以实现在对象级的网络检索。我们搜集与某…

C# 定时器定时更新

class Program{static void Main(string[] args){//for (int i 0; i < 100; i)//{// SendMessage("131", "131");//}System.Timers.Timer aTimer new System.Timers.Timer();aTimer.Elapsed new ElapsedEventHandler(aTimer_Elapsed);// 设置引发…

前端vscode常用插件

Auto Rename Tag 这是一个html标签的插件&#xff0c;可以让你修改一边标签&#xff0c;另外一边自动改变。 Beautify 格式化代码插件 Braket Pair Colorizer 给js文件中的每一个小括号()花括号{}都配上不同的颜色&#xff0c;方便找到哪一个位置多了少了括号。 Debugger for C…

在线条形码生成器

条形码又称条码、一维码&#xff0c;是将字符按照特定的规则转化成二进制后&#xff0c;描绘成一个宽度不等的多个黑条和空白&#xff0c;按照一定的编码规则排列的图形标识符&#xff0c;条形码现在应用相当广泛&#xff0c;一出门&#xff0c;随便翻一样东西&#xff0c;可能…

装箱拆箱

1、 装箱和拆箱是一个抽象的概念 2、 装箱是将值类型转换为引用类型 &#xff1b;拆箱是将引用类型转换为值类型 利用装箱和拆箱功能&#xff0c;可通过允许值类型的任何值与Object 类型的值相互转换&#xff0c;将值类型与引用类型链接起来 例如&#xf…

[JSOI2008 Prefix火星人]

[关键字]&#xff1a;splay hash 二分 [题目大意]&#xff1a;给出一个字符串&#xff0c;求出给定的两个后缀的的最长公共前缀。在求的过程中会有改变或在某个位置添加字符的操作。 // [分析]&#xff1a;一听最长公共前缀马上想到后缀数组&#xff0c;但因为是动态维护所以后…

简单实用方法!!

简单验证码生成&#xff01;&#xff01; protected void Page_Load(object sender, EventArgs e) { string CharList "0123456789"; int[] size { 10, 12, 14 }; string[] fm { "宋体", "楷体_G…

浅谈微信小程序生命周期

之前在做微信小程序的时候&#xff0c;一直对生命周期里面的onLoad&#xff0c;onShow&#xff0c;onUnload不是很理解。比如说什么时候会触发onUnload。 经过一段时间的测试发现&#xff0c;普通页面的onUnload在三种情况下会触发。 某一个页面跳转到tabBar页面&#xff0c;根…

POJ 1013 Counterfeit Dollar 称硬币

12个硬币&#xff0c;有一个假的 或轻或重&#xff0c;找出假硬币 开始用的模拟&#xff0c;考虑很多情况 后来&#xff0c;lmy说轻的-1&#xff0c;重的1&#xff0c;学数学的看什么都是数字&#xff0c;orz 模拟写的两个差不多的代码&#xff1a; (一&#xff09; #include&l…

DELPHI学习---结构类型

Structured types (结构类型) 结构类型的一个实例可包含多个值。结构类型包括集合、数组、记录&#xff0c;也包括类、类引用&#xff08;class-reference&#xff09; 和接口类型。除了集合只能包含有序值以外&#xff0c;结构类型可以包含其它的结构类型&#xff0c;且结构的…

ios学习笔记block回调的应用(一个简单的例子)

一、什么是Blocks Block是一个C级别的语法以及运行时的一个特性&#xff0c;和标准C中的函数&#xff08;函数指针&#xff09;类似&#xff0c;但是其运行需要编译器和运行时支持&#xff0c;从ios4.0开始就很好的支持Block。 二、在ios开发中&#xff0c;什么情况下使用…

vue定义global.js,挂载在vue原型上面使用

首先在src目录下创建global目录&#xff0c;在global目录下创建index.js。 export default {install(Vue) {var that this// 1. 添加全局方法或属性// ue.global this// 2. 添加全局资源// 3. 注入组件Vue.mixin({created() {this.global that}})// 大于一的整数验证&#x…

Configuration、SessionFactory、Session

org.hibernate.cfg Class Configuration An instance of Configuration allows(允许) the application to specify properties and mapping documents to be used when creating a SessionFactory. Usually an application will create a single Configuration, build a singl…

函数声明指令(stdcall, cdecl,pascal,register)

指令 参数存放位置 参数传递顺序 参数内存管理 适用地点registerCPU寄存器从左到右被调用者默认&#xff0c;published 属性存取方法必须使用pascal栈从左到右被调用者向后兼容cdecl栈从右到左调用者调用 C 共享库stdcall栈从右到左被调用者API 调用safecall栈从右到左被调用…

uni-app相关

uni-app 中以下组件的高度是固定的&#xff0c;不可修改&#xff1a; 导航栏高度固定为 44pxtabBar 高度固定为 56px 状态栏比较特殊&#xff0c;是一个变量 .status_bar{height: var(--status-bar-height);width: 100%; } uni-app 使用 vue/cli 创建项目的时候&#xff0c;如果…

《Windows游戏编程大师技巧》三、Windows高级编程

Windows编程很绝的地方在于&#xff1a;你不用了解太多细节&#xff0c;就可以完成很多工作。使用资源资源就是你的程序代码结合在一起的多块数据&#xff0c;可以被程序本身在运行时加载。资源应当也放在程序的.EXE文件中的原因是&#xff1a;1.同时包含代码和数据的.EXE文件更…

结构型模式--装饰模式

下面先用java&#xff0c;然后用Objective&#xff0d;C行对装饰模式的讲解&#xff1a; 对于java的装饰模式讲解和使用比较详细和难度有点偏高&#xff0c;而对于Objective&#xff0d;C的装饰模式讲解和使用方面比较简单&#xff0c;而且和java的装饰模式略有差异&#xff0c…

ArcGIS.Server.9.2.DotNet自带例子分析(三、一)

目的&#xff1a; 1.arcgis server9.2 ADF的AddGraphics。 准备工作&#xff1a; 1.用ArcGis Server Manager或者ArcCatalog发布一个叫world的Map Service,并且把这个Service启动起来。 2.找到DeveloperKit\SamplesNET\Server\Web_Applications目录下的Common_AddGraphicsCShar…