您的位置:首页 > 其它

基于新浪微博api的微博分享功能实现

2013-05-06 15:01 399 查看
首先应该拿到新浪微博开发的api,然后细读其中的一些文档规范,这样我们就能知道第三方应用要想实现分享内容到新浪微博平台,

1.第三方应用需要在新浪微博的开放平台通过审核,拿到

<span style="font-family:Microsoft YaHei;font-size:14px;">client_ID=*****
client_SERCRET=*****</span>
配置到config.properties,信息如下:

<span style="font-family:Microsoft YaHei;font-size:14px;">client_ID=*****
client_SERCRET=*****
redirect_URI=http://apps.weibo.com/ceshidemo
baseURL=https://api.weibo.com/2/
accessTokenURL=https://api.weibo.com/oauth2/access_token
authorizeURL=https://api.weibo.com/oauth2/authorize
rmURL=https://rm.api.weibo.com/2/
response_type=code</span>
2.拿着从新浪微博开放平台获取的client_ID、client_SERCRET去获取AccessToken,

3.然后拿着获取的AccessToken去访问新浪微博,发送一篇心得微博或者是获取当前用户信息等等

下面是代码:

<span style="font-family:Microsoft YaHei;font-size:14px;">public class WeiBoUtil2 extends WeiBoUtil {

public static final String POST_WEIBO_URL_WITH_CONTENT = "https://api.weibo.com/2/statuses/update.json?";

private static final Logger logger = Logger.getLogger(WeiBoUtil2.class);

public static Map<String, String> header = new HashMap<String, String>();

static {

header.put("Accept-Language", "zh-CN,zh;q=0.8");

header.put("User-Agent", "test sina api");

header.put("Accept-Charset", "utf-8;q=0.7,*;q=0.3");
}

/**
* 获取当前用户信息
*
* @param uid
*
*/
public static void showUser(String uid) {
Weibo weibo = new Weibo();
AccessToken accessToken = weibo.getAccessToken();// 通过code回去通行令类
Users um = new Users();
um.client.setToken(accessToken.getAccessToken());// 设置通行令然后发布微博
try {
User user = um.showUserById(uid);// 获取用户
Log.logInfo(user.toString());
} catch (WeiboException e) {
e.printStackTrace();
}
}

/**
* 获取用户的粉丝列表
*
* @param name
* @throws WeiboException
* when Weibo service or network is unavailable
*/
public static void findFriendsByScreenName(String name) {
Weibo weibo = new Weibo();
AccessToken accessToken = weibo.getAccessToken();
Friendships fm = new Friendships();
fm.client.setToken(accessToken.getAccessToken());
try {
UserWapper users = fm.getFollowersByName(name);
for (User u : users.getUsers()) {
Log.logInfo(u.toString());
}
} catch (WeiboException e) {
Log.logErr(null+ ":" + e.getMessage());
}
}

/**
* 获取通行令方法
*
* @param userid
* 用户名
* @param password
* 密码
* @return AccessToken 通行令
* @throws WeiboException
* when userId or password is not OAuth HttpException when Weibo
* service or network is unavailable
* @author
*/
public static AccessToken refreshToken(String userid, String password) {
try {
String url = WeiboConfig.getValue("authorizeURL");// 微博认证授权地址
PostMethod postMethod = new PostMethod(url);

postMethod.addParameter("client_id", WeiboConfig
.getValue("client_ID"));// your client id
postMethod.addParameter("redirect_uri", WeiboConfig
.getValue("redirect_URI"));// your url
postMethod.addParameter("userId", userid);// 获取微薄的useid
postMethod.addParameter("passwd", password);
postMethod.addParameter("isLoginSina", "0");
postMethod.addParameter("action", "submit");
postMethod.addParameter("response_type", WeiboConfig
.getValue("response_type"));// code

// 获取post方法的参数
HttpMethodParams param = postMethod.getParams();
param.setContentCharset("UTF-8");// 进行编码转换

List<Header> headers = new ArrayList<Header>();
// 伪造请求头信头
headers.add(new Header(
"Referer",
"https://api.weibo.com/oauth2/authorize?client_id=your_client_id&redirect_uri=your_redirect_url&from=sina&response_type=code"));
headers.add(new Header("Host", "api.weibo.com"));
// headers
// .add(new Header("User-Agent",
// "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));

headers.add(new Header("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0)"));

ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", fcty, 443));

//HttpClient客户端apache下面的api
HttpClient client = new HttpClient();
client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
client.executeMethod(postMethod);
//获得响应的状态码
int status = postMethod.getStatusCode();

if (status != 200 && status != 302) {
Log.logErr("请求Token返回的状态码:" + status);
}
// 获取响应的头信息中的 地址信息
Header location = postMethod.getResponseHeader("Location");
// 下面的方法是取出code
if (location != null) {
String retUrl = location.getValue();
int begin = retUrl.indexOf("code=");
if (begin != -1) {
int end = retUrl.indexOf("&", begin);
if (end == -1)
end = retUrl.length();
String code = retUrl.substring(begin + 5, end);
if (code != null) {
// 通过getAccessTokenByCode方法返回accessToken
Log.logInfo("location's code is :" + code);
return new Oauth().getAccessTokenByCode(code);
}
}
} else {
Log.logErr("location's code is :"+location);
}
} catch (WeiboException e) {
Log.logErr(e.getMessage());
} catch (HttpException e) {
Log.logErr(null);
} catch (IOException e) {
Log.logErr(e.getMessage());
}
Log.logErr("refresh token failed");
return null;
}

/**
* 发布一篇微博方法
*
* @param str
* 发送的微博正文
* @param userid
* 用户ID
* @param password
* 用户密码
* @return String post请求返回的response内容
*/
public static String sendWeibo(String str, String userid, String password,
String accessToken) throws WeiboException {
Map<String, String> params = new HashMap<String, String>();

params.put("access_token", accessToken);
params.put("status", str);
params.put("lat", "39.920063467669495");
params.put("long", "116.46009815979004");

String respStr = postMethodRequestWithOutFile(POST_WEIBO_URL_WITH_CONTENT, params, header);
Log.logInfo("postMethodRequestWithOutFile responce-->" + respStr);
return respStr;
}

/**
* post请求发送方法
*
* @param url
* 发布微博的地址
* @param params
* 请求消息头中的参数值
* @param header
* 请求头信息
* @return 服务器端的响应信息
* @throws WeiboException
* when userId or password is not OAuth HttpException
* Exception when Weibo service or network is unavailable
*/
public static String postMethodRequestWithOutFile(String url,
Map<String, String> params, Map<String, String> header) {

Log.logInfo("post request is begin! url =" + url);

HttpClient hc = new HttpClient();

try {
PostMethod pm = new PostMethod(url);
if (header != null) {
for (String head_key : header.keySet()) {
if (head_key == null || header.get(head_key) == null)
continue;
pm.addRequestHeader(head_key, header.get(head_key));
}
}
if (params != null) {
for (String param_key : params.keySet()) {
if (param_key == null || params.get(param_key) == null)
continue;
pm.addParameter(param_key, params.get(param_key));
}
}
// 获取params,然后进行编码,编成utf8格式
pm.getParams().setContentCharset("utf8");
hc.executeMethod(pm);
String ret = pm.getResponseBodyAsString();// 获取响应体的字符串
Log.logInfo("post请求发出后返回的信息:" + ret);
return ret;
} catch (HttpException e) {
Log.logErr(null);
} catch (Exception e) {
Log.logErr(null);
} finally {
Log.logInfo("post request is end! url =" + url);
}
return null;
}</span>

如有兴趣获取更多资料:加下求:378437335
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: