Java使用新浪微博API通过账号密码方式登陆微博的实例
作者:冰冻鱼 发布时间:2023-09-23 05:35:38
标签:Java,微博
今天下了个新浪微博的API研究研究,目前实现了发布微博功能,包括带图片的微博。为了安全,新浪微博的API中并没有提供用微博帐号密码登录的功能,而是采用OAuth授权,用户通过浏览器访问新浪网站登录,登录成功后,浏览器再返回key和secret给程序。
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/login"
android:text="登录" />
<EditText android:id="@+id/status" android:layout_width="fill_parent"
android:layout_height="300sp" android:hint="输入微博消息" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/send"
android:text="发布" />
</LinearLayout>
一个登录按钮,一个输入框,一个发布按钮
因为要接收浏览器返回的数据,所以,AndroidManifest.xml注册Activity的时候要加个Intent-Filter
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pocketdigi.weibo" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sina" android:host="weibo" />
<!-- 监控sina://weibo这样的地址 -->
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
intent-filter必须分成两段写,如果合在一起写,就启动不了了。
为了简便,直接把新浪Sample里的OAuthConstant类拷过来:
package weibo4android.androidexamples;
import weibo4android.Weibo;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
public class OAuthConstant {
private static Weibo weibo=null;
private static OAuthConstant instance=null;
private RequestToken requestToken;
private AccessToken accessToken;
private String token;
private String tokenSecret;
private OAuthConstant(){};
public static synchronized OAuthConstant getInstance(){
if(instance==null)
instance= new OAuthConstant();
return instance;
}
public Weibo getWeibo(){
if(weibo==null)
weibo= new Weibo();
return weibo;
}
public AccessToken getAccessToken() {
return accessToken;
}
public void setAccessToken(AccessToken accessToken) {
this.accessToken = accessToken;
this.token=accessToken.getToken();
this.tokenSecret=accessToken.getTokenSecret();
}
public RequestToken getRequestToken() {
return requestToken;
}
public void setRequestToken(RequestToken requestToken) {
this.requestToken = requestToken;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getTokenSecret() {
return tokenSecret;
}
public void setTokenSecret(String tokenSecret) {
this.tokenSecret = tokenSecret;
}
}
接下来就是最关键的主程序:
package com.pocketdigi.weibo;
import java.io.File;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
/** Called when the activity is first created. */
String key = "", secret = "";
Button login,send;
EditText status;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.setProperty("weibo4j.oauth.consumerKey", "3997936609");
System.setProperty("weibo4j.oauth.consumerSecret",
"8bc9e3bfd6ae8e3b2b8bda9079918950");
//设置在新浪应用开放平台申请的应用的key和secret
login=(Button)findViewById(R.id.login);
send=(Button)findViewById(R.id.send);
status=(EditText)findViewById(R.id.status);
login.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
login();
//登录
}});
send.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text=String.valueOf(status.getText());
Weibo weibo = new Weibo();
weibo.setToken(key,secret);
try {
//weibo.updateStatus(text);
//只发文字
File f=new File("/sdcard/wallpaper/129567208597069400.jpg");
weibo.uploadStatus(text,f );
//发文字+图片,这里需要导入commons-httpclient-3.0.1.jar,自己网上下
//在实际项目上,最好放Thread里,因为按下去的时候按钮会卡
} catch (WeiboException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//启动时执行检测是否来自网页登录返回
//如果是,获取key和secret
//否则读取SharedPreferences
//若得不到key和secret,直接跳转登录
Uri uri = this.getIntent().getData();
if (uri != null) {
//如果是浏览器返回
try {
RequestToken requestToken = OAuthConstant.getInstance()
.getRequestToken();
AccessToken accessToken = requestToken.getAccessToken(uri
.getQueryParameter("oauth_verifier"));
OAuthConstant.getInstance().setAccessToken(accessToken);
// 保存
Editor sharedata = getSharedPreferences("WeiBo", 0).edit();
sharedata.putString("key", accessToken.getToken());
sharedata.putString("secret", accessToken.getTokenSecret());
sharedata.commit();
key = accessToken.getToken();
secret = accessToken.getTokenSecret();
} catch (WeiboException e) {
e.printStackTrace();
}
} else {
//如果是用户自己启动
SharedPreferences settings = getSharedPreferences("WeiBo", 0);
key = settings.getString("key", "");
secret = settings.getString("secret", "");
}
if (key.equals("") || secret.equals("")) {
Toast.makeText(this, "尚未登录", Toast.LENGTH_LONG).show();
login();
//跳转到浏览器登录
}
}
public void login(){
Weibo weibo = OAuthConstant.getInstance().getWeibo();
RequestToken requestToken;
try {
requestToken =weibo.getOAuthRequestToken("sina://weibo");
//为了避免与同类应用冲突,还是自己改下URI吧
Uri uri2 = Uri.parse(requestToken.getAuthenticationURL()+ "&from=xweibo");
OAuthConstant.getInstance().setRequestToken(requestToken);
startActivity(new Intent(Intent.ACTION_VIEW, uri2));
} catch (WeiboException e) {
e.printStackTrace();
}
}
}
发图片需要导入commons-httpclient-3.0.1.jar,否则启动报错,当然weibo4android-1.2.0.jar是不可少的


猜你喜欢
- java 中Spark中将对象序列化存储到hdfs摘要: Spark应用中经常会遇到这样一个需求: 需要将JAVA对象序列化并存储到HDFS
- 更新: 工作中突然想起来,关于Yaml的使用,并不属于Spring的范畴,是org.yaml.snakeyaml处理的。所以yaml的使用应
- 前面一篇文章我们介绍了使用CAS算法实现的非阻塞队列ConcurrentLinedQueue, 下面我们来介绍使用独占锁实现的阻塞队列Lin
- 本文实例讲述了C#清除字符串内空格的方法,分享给大家供大家参考。具体如下:关键代码如下:/// <summary>/// 清除字
- 本文实例介绍了Android实现ImageView图片双击放大及缩小的相关技巧,分享给大家供大家参考,具体内容如下public class
- 本文实例讲述了Android实现手机壁纸改变的方法。分享给大家供大家参考。具体如下:main.xml布局文件:<?xml versio
- 前言经过前面对 Kotlin 的介绍,相信大家已经能对 Kotlin 有了一个基本的认识。 从这节开始,我就为大家讲解 Kotlin的方法以
- Properties属性文件中的值有等号和换行Spring配置Shiro的过滤器时,有个filterChainDefinitions属性,值
- 网上很多人对设置控件的位置都使用view.setPadding(left, top, right, bottom) ,其实这玩意很差劲,它是
- 前言在java里,当我们需要拷贝一个对象时,有两种类型的拷贝:浅拷贝与深拷贝。浅拷贝只是拷贝了源对象的地址,所以源对象的值发生变化时,拷贝对
- 前言最近工作上遇到很多批量插入的场景,但是百度很难得到我想要的结果,而且查出来的效果不是很好~所以就自己来写一份给大家参考,希望对大家有用M
- EventBus 可以很方便地进行各组件间的通信,解耦性更强,比广播更好用。EventBus 3 简介EventBus是一种为了优化Andr
- 博主说:有时候,我们需要对数据库中现有的数据进行大量处理操作(例如表中的某个字段需要全部更新等),如果直接使用select * from t
- 本文实例为大家分享了Java实现员工管理系统的具体代码,供大家参考,具体内容如下本系统主要练习到的相关内容: 1、 流程控制语句 2、 类、
- 目录前言实践部分测试部分总结前言今天跟小伙伴们分享一个实战内容,使用Spring Boot+Shiro实现一个简单的Http认证。场景是这样
- Contact联系人对Mms来说是十分重要的,因为每一个对话的收信人都是一个联系人,新建信息时可以输入联系人的任何信息,比如号码或名字,Mm
- Thread生命周期生命周期概述Java的线程状态描述放在Thread类里面的枚举类State中.总共包含了6中状态(从出生到死亡)。pub
- 自定义 webflux 容器配置配置代码@Componentpublic class ContainerConfig extends Rea
- 很久没写文章了,一方面是最近几个月比较忙,没太多时间,另一方面是最近拖延症严重,写文章的想法总是一拖再拖。今天找一个小案例写一下,与懒惰对抗
- boot-admin整合Quartz实现动态管理定时任务淄博烧烤爆红出了圈,当你坐在八大局的烧烤摊,面前是火炉、烤串、小饼和蘸料,音乐响起,