第三方应用如何拿到新浪微博开发的api,然后呢?

优采云 发布时间: 2021-03-29 00:18

  第三方应用如何拿到新浪微博开发的api,然后呢?

  首先,我们应该获取由新浪微博开发的API,然后阅读一些文档规范,以便我们可以知道第三方应用程序希望与新浪微博平台共享内容,

  1.第三方应用程序需要在新浪微博的开放平台上进行审核才能获得

  client_ID=*****

client_SERCRET=*****

  配置为config.properties,信息如下:

  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

  2.使用从新浪微博开放平台获得的client_ID和client_SERCRET来获取AccessToken,

  3.然后使用获取的AccessToken访问新浪微博,发送体验微博或获取当前用户信息,等等。

  这是代码:

  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 header = new HashMap();

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 headers = new ArrayList();

// 伪造请求头信头

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 params = new HashMap();

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 params, Map 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;

}

  如果您有兴趣获取更多信息,请添加以下请求:378437335

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线