当前位置: 移动技术网 > IT编程>开发语言>Java > Java模拟新浪和腾讯自动登录并发送微博

Java模拟新浪和腾讯自动登录并发送微博

2019年07月22日  | 移动技术网IT编程  | 我要评论

java模拟新浪和腾讯自动登录并发送微博功能分享给大家,供大家参考,具体内容如下

1.准备工作
只是登录无需申请新浪和腾迅的开发者账号,如果需要发送微博功能,需要申请一个新浪和腾迅的开发者账号,并添加一个测试应用。 

过程请参考官方帮助文档,申请地址:新浪:http://open.weibo.com    腾迅: 

我们需要的是app key和app secre及redirect_uri,源代码中已经包含了我申请的测试key,但由于限制直接用我的key你们的账号是无法登录成功的。 

2.注意事项
 1)、需要注意的是应用的app key和app secre及redirect_uri,对应项目根目录下的config.properties配置文件中的
client_id=1745656892
client_sercret=66056719c1d8ca7bcaf36f411217cefa
redirect_uri=www.baidu.com
redirect_uri由于只是测试用并没有直接的回调页面,所以这里随便填写一个地址就行了,但要注意与应用-高级设置里的“回调页面”一致。 
2)、代码中的测试账号需要要自己添加测试账号,新浪的在“应用信息-测试账号”;腾迅的在“权限控制-创建白名单”中。当然直接用 开发者账号也可以。
3)、发送微博引用了新浪的weibo4j-oauth2-beta2.1.1.zip,腾迅的java_sdk_v1.2.1.7z。核心类在util包下。

3.关键代码
1)、新浪 

package org.utils;
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;

import org.apache.commons.httpclient.header;
import org.apache.commons.httpclient.httpclient;
import org.apache.commons.httpclient.methods.postmethod;
import org.apache.commons.httpclient.params.httpmethodparams;
import org.apache.http.httpexception;
import org.core.weibo.sina.oauth;
import org.core.weibo.sina.timeline;
import org.core.weibo.sina.http.accesstoken;
import org.core.weibo.sina.model.weiboexception;
import org.core.weibo.sina.weibo4j.util.weiboconfig;
/***
 * 模拟自动登录并发微博
 * @author zdw
 *
 */
public class sina {
 /***
 * 模拟登录并得到登录后的token
 * @param username 用户名
 * @param password 密码
 * @return
 * @throws httpexception
 * @throws ioexception
 */
 public static accesstoken gettoken(string username,string password) throws httpexception, ioexception 
 {
  string clientid = weiboconfig.getvalue("client_id") ;
  string redirecturi = weiboconfig.getvalue("redirect_uri") ;
  string url = weiboconfig.getvalue("authorizeurl");
  
  postmethod postmethod = new postmethod(url);
  //应用的app key 
  postmethod.addparameter("client_id",clientid);
  //应用的重定向页面
  postmethod.addparameter("redirect_uri",redirecturi);
  //模拟登录参数
  //开发者或测试账号的用户名和密码
  postmethod.addparameter("userid", username);
  postmethod.addparameter("passwd", password);
  postmethod.addparameter("isloginsina", "0");
  postmethod.addparameter("action", "submit");
  postmethod.addparameter("response_type","code");
  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="+clientid+"&redirect_uri="+redirecturi+"&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"));
  httpclient client = new httpclient();
  client.gethostconfiguration().getparams().setparameter("http.default-headers", headers);
  client.executemethod(postmethod);
  int status = postmethod.getstatuscode();
  system.out.println(status);
  if (status != 302)
  {
  system.out.println("token刷新失败");
  return null;
  }
  //解析token
  header location = postmethod.getresponseheader("location");
  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) {
   oauth oauth = new oauth();
   try{
    accesstoken token = oauth.getaccesstokenbycode(code);
    return token;
   }catch(exception e){
    e.printstacktrace();
   }
   }
  }
  }
 return null;
 }
 /**
 * 发微博
 * @param token 认证token
 * @param content 微博内容
 * @return
 * @throws exception
 */
 public static boolean sinasendweibo(string token,string content) throws exception {
 boolean flag = false ;
 timeline timeline = new timeline();
 timeline.client.settoken(token);
 try 
 {
  timeline.updatestatus(content);
  flag = true ;
 } 
 catch (weiboexception e) 
 {
  flag = false ;
  system.out.println(e.geterrorcode());
 }
 return flag;
 }
 
 public static void main(string[] args) throws exception
 {
 accesstoken at = gettoken("xxxx","xxx");
 sinasendweibo(at.getaccesstoken(),"测试呢");
 }
}

 

2)、腾迅 

package org.utils;

import java.io.bytearrayoutputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.outputstream;
import java.io.unsupportedencodingexception;
import java.security.messagedigest;
import java.util.scanner;

import net.sf.json.jsonobject;

import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.client.clientprotocolexception;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.util.entityutils;
import org.core.weibo.tencent.api.userapi;
import org.core.weibo.tencent.oauthv2.oauthv2;
import org.core.weibo.tencent.oauthv2.oauthv2client;

/***
 * 腾迅自动登录并获取个人信息
 * @author zdw
 *
 */
public class tencent
{
 public static final string hexstring = "0123456789abcdef";
 public static oauthv2 oauth = new oauthv2();
 private static httpclient client = new defaulthttpclient();
 // 初始oauth应用信息
 public static void init(oauthv2 oauth)
 {
 oauth.setclientid("801216331");
 oauth.setclientsecret("ea71b26b0cbe5778cdd1c09ad17553a3");
 oauth.setredirecturi("http://www.tencent.com/zh-cn/index.shtml");
 }
 /**
 * 
 * @param qq
 *      http://check.ptlogin2.qq.com/check?uin={0}&appid=15000101&r={1 }
 *      返回的第三个值
 * @param password
 *      qq密码
 * @param verifycode
 *      验证码
 * @return 加密后的密码
 * @throws unsupportedencodingexception
 * @throws exception
 * 
 */
 public static string getpassword(string qq, string password,
  string verifycode) throws exception
 {
 string p = hexchar2bin(md5(password));
 string u = md5(p + hexchar2bin(qq.replace("\\x", "").touppercase()));
 string v = md5(u + verifycode.touppercase());
 return v;
 }
 
 public static string md5(string originaltext) throws exception
 {
 byte buf[] = originaltext.getbytes("iso-8859-1");
 stringbuffer hexstring = new stringbuffer();
 string result = "";
 string digit = "";
 try
 {
  messagedigest algorithm = messagedigest.getinstance("md5");
  algorithm.reset();
  algorithm.update(buf);
  byte[] digest = algorithm.digest();
  for (int i = 0; i < digest.length; i++)
  {
  digit = integer.tohexstring(0xff & digest[i]);
  if (digit.length() == 1)
  {
   digit = "0" + digit;
  }
  hexstring.append(digit);
  }
  result = hexstring.tostring();
 }
 catch (exception ex)
 {
  result = "";
 }
 return result.touppercase();
 }

 public static string hexchar2bin(string md5str) throws unsupportedencodingexception
 {
 bytearrayoutputstream baos = new bytearrayoutputstream(md5str.length() / 2);
 for (int i = 0; i < md5str.length(); i = i + 2)
 {
  baos.write((hexstring.indexof(md5str.charat(i)) << 4 | hexstring
   .indexof(md5str.charat(i + 1))));
 }
 return new string(baos.tobytearray(), "iso-8859-1");
 }
 /***
 * 模拟登录
 * @param qq qq号码 
 * @param password qq密码
 * @throws exception
 */
 public static void login(string qq, string password) throws exception
 {
 httpget get = new httpget("https://ssl.ptlogin2.qq.com/check?uin="+ qq + "&appid=46000101&ptlang=2052&js_type=2&js_ver=10009&r=0.7948186025712065");
 httpresponse response = client.execute(get);
 string entity = entityutils.tostring(response.getentity());
 string[] checknum = entity.substring(entity.indexof("(") + 1,entity.lastindexof(")")).replace("'", "").split(",");
 string pass = "";
 string responsedata = "";
 // 获取验证码(如果有验证码输出到c:/code.jpg,查看后输入可继续执行
 if ("1".equals(checknum[0]))
 {
  // uin为qq号或者微博用户名
  httpget getimg = new httpget("http://captcha.qq.com/getimage?aid=46000101&r=0.3478789969909082&uin=" + qq + "&vc_type=" + checknum[1] + "");
  httpresponse response2 = client.execute(getimg);
  outputstream os = new fileoutputstream("c:/code.jpg");
  byte[] b = entityutils.tobytearray(response2.getentity());
  os.write(b, 0, b.length);
  os.close();
  scanner in = new scanner(system.in);
  responsedata = in.nextline();
  in.close();
 }
 else
 {
  responsedata = checknum[1];
 }
 /** *******************加密密码 ************************** */
 pass = getpassword(checknum[2], password, responsedata);
 /** *********************** 登录 *************************** */
 httpget getimg = new httpget("https://ssl.ptlogin2.qq.com/login?ptlang=2052&u="+ qq+ "&p="+ pass+ "&verifycode="+ responsedata+ "&aid=46000101&target=top&u1=https%3a%2f%2fopen.t.qq.com%2fcgi-bin%2foauth2%2fauthorize%3fclient_id%3d"
   + oauth.getclientid()+ "%26response_type%3dcode%26redirect_uri="+ oauth.getredirecturi()+ "&ptredirect=1&h=1&from_ui=1&dumy=&qlogin_param=abbfew=ddd&wording=%e6%8e%88%e6%9d%83&fp=loginerroralert&action=8-13-240977&g=1&t=1&dummy=&js_type=2&js_ver=10009");
 httpresponse response2 = client.execute(getimg);
 httpentity httpentity = response2.getentity();
 string entityxc = entityutils.tostring(httpentity);
 system.out.println(entityxc);
 }

 /**
 * 
 * 请求微博开放平台应用 返回登录授权页面,但是如果没有sessionkey的话永远登录不成功 sessionkey
 * 发现在返回的页面中一个input标签里放的url中有,所以要取到这个sessionkey 其实直接访问标签中的url就可以跳转
 * 
 */
 public static string geturl() throws clientprotocolexception, ioexception
 {
 httpget getcode = new httpget("https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id="+ oauth.getclientid()+ "&response_type=code&redirect_uri="
     + oauth.getredirecturi()+ "&checkstatus=yes&appfrom=&g_tk&checktype=showauth&state=");
 httpresponse response3 = client.execute(getcode);
 httpentity entityqqq = response3.getentity();
 string entityxcc = entityutils.tostring(entityqqq);
 string form = entityxcc.substring(entityxcc.indexof("<form"), entityxcc
  .indexof("</form>"));
 string[] ss = form.split("/>");
 string input = "";
 for (int i = 0; i < ss.length; i++)
 {
  if (ss[i].indexof("name=\"u1\"") > 0)
  {
  input = ss[i];
  }
  ;
 }
 return input.substring(input.indexof("value=\"") + 7, input.indexof("\" type=\""));
 }
 /**
 * 解析并设置token
 * @param get
 * @throws exception 
 */
 public static void settoken(httpget get) throws exception
 {
 httpresponse response4 = client.execute(get);
 httpentity entityqqq1 = response4.getentity();
 string geturlcode = entityutils.tostring(entityqqq1);
 // 返回了最终跳转的页面url,也就是回调页redirect_uri,页面地址上包含code openid openkey
 // 需要将这三个值单独取出来再拼接成 code=xxxxx&openid=xxxxx&openkey=xxxxxx的形式
 string entity = geturlcode.substring(geturlcode.indexof("url="),geturlcode.indexof("\">"));
 stringbuffer sb = new stringbuffer();
 string[] arr = entity.split("\\?")[1].split("&");
 for (int x = 0; x < arr.length; x++)
 {
  if (arr[x].indexof("code") >= 0 || arr[x].indexof("openid") >= 0
   || arr[x].indexof("openkey") >= 0)
  {
  sb.append(arr[x] + "&");
  }
  ;
 }
 // 利用code获取accesstoken
 oauthv2client.parseauthorization(sb.substring(0, sb.length() - 1), oauth);
 oauth.setgranttype("authorize_code");
 oauthv2client.accesstoken(oauth);
 }
 /***
 * 调用(腾迅开放平台账户接口)获取一个人的信息
 * @throws exception 
 */
 public static void getinfo() throws exception
 {
 //输出token,如果拿到了token就代表登录成功,并可以进行下一步操作。
 system.out.println("token="+oauth.getaccesstoken());
 userapi getuser = new userapi(oauth.getoauthversion());
 string userjson = getuser.otherinfo(oauth, "json", "", oauth.getopenid());
 jsonobject userjsonobject = jsonobject.fromobject(userjson);
 integer errcode = (integer) userjsonobject.get("errcode");
 if (errcode == 0)
 {
  jsonobject userdatajsonobject = (jsonobject) userjsonobject.get("data");
  system.out.println(userdatajsonobject.tostring());
 }
 }
 
 public static void main(string[] args) throws exception
 {
 init(oauth);
 login("123145", "xxxx");
 httpget get = new httpget(geturl());
 settoken(get);
 getinfo();
 }



}

4.发送成功都有对应的日志输出
新浪(最后一行日志):

 2078 debug [2013-03-14 16:35:29]  {"created_at":"thu mar 14 16:35:30 +0800 2013","id":3555791132949940,"mid":"3555791132949940","idstr":"3555791132949940","text":"测试呢","source":"...

腾迅:

登录成功的日志标志: 
ptuicb('0','0','https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=801216331&response_type=code&redirect_uri=http:','1','登录成功!', 'ㄗs:ヤ淡 啶');查看个人信息成功后的日志标志: 

qhttpclient httpget [3] response = {"data":{"birth_day":26,"birth_month":8,"birth_year":2011,"city_code":"2","comp":null,"country_code":"1","edu":null,"email":"","exp":141,"fansnum":..

日志未全列出,只是作为参考。

源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网