Java模拟新浪和腾讯自动登录并发送微博
Java模拟新浪和腾讯自动登录并发送微博功能分享给大家,供大家参考,具体内容如下
1.准备工作
只是登录无需申请新浪和腾迅的开发者账号,如果需要发送微博功能,需要申请一个新浪和腾迅的开发者账号,并添加一个测试应用。
过程请参考官方帮助文档,申请地址:新浪:http://open.weibo.com 腾迅:http://dev.t.qq.com/
我们需要的是AppKey和AppSecre及redirect_URI,源代码中已经包含了我申请的测试key,但由于限制直接用我的key你们的账号是无法登录成功的。
2.注意事项
1)、需要注意的是应用的AppKey和AppSecre及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)、新浪
packageorg.utils; importjava.io.IOException; importjava.util.ArrayList; importjava.util.List; importorg.apache.commons.httpclient.Header; importorg.apache.commons.httpclient.HttpClient; importorg.apache.commons.httpclient.methods.PostMethod; importorg.apache.commons.httpclient.params.HttpMethodParams; importorg.apache.http.HttpException; importorg.core.weibo.sina.Oauth; importorg.core.weibo.sina.Timeline; importorg.core.weibo.sina.http.AccessToken; importorg.core.weibo.sina.model.WeiboException; importorg.core.weibo.sina.weibo4j.util.WeiboConfig; /*** *模拟自动登录并发微博 *@authorzdw * */ publicclassSina{ /*** *模拟登录并得到登录后的Token *@paramusername用户名 *@parampassword密码 *@return *@throwsHttpException *@throwsIOException */ publicstaticAccessTokengetToken(Stringusername,Stringpassword)throwsHttpException,IOException { StringclientId=WeiboConfig.getValue("client_ID"); StringredirectURI=WeiboConfig.getValue("redirect_URI"); Stringurl=WeiboConfig.getValue("authorizeURL"); PostMethodpostMethod=newPostMethod(url); //应用的AppKey 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"); HttpMethodParamsparam=postMethod.getParams(); param.setContentCharset("UTF-8"); //添加头信息 List<Header>headers=newArrayList<Header>(); headers.add(newHeader("Referer","https://api.weibo.com/oauth2/authorize?client_id="+clientId+"&redirect_uri="+redirectURI+"&from=sina&response_type=code")); headers.add(newHeader("Host","api.weibo.com")); headers.add(newHeader("User-Agent","Mozilla/5.0(WindowsNT6.1;rv:11.0)Gecko/20100101Firefox/11.0")); HttpClientclient=newHttpClient(); client.getHostConfiguration().getParams().setParameter("http.default-headers",headers); client.executeMethod(postMethod); intstatus=postMethod.getStatusCode(); System.out.println(status); if(status!=302) { System.out.println("token刷新失败"); returnnull; } //解析Token Headerlocation=postMethod.getResponseHeader("Location"); if(location!=null) { StringretUrl=location.getValue(); intbegin=retUrl.indexOf("code="); if(begin!=-1){ intend=retUrl.indexOf("&",begin); if(end==-1) end=retUrl.length(); Stringcode=retUrl.substring(begin+5,end); if(code!=null){ Oauthoauth=newOauth(); try{ AccessTokentoken=oauth.getAccessTokenByCode(code); returntoken; }catch(Exceptione){ e.printStackTrace(); } } } } returnnull; } /** *发微博 *@paramtoken认证Token *@paramcontent微博内容 *@return *@throwsException */ publicstaticbooleansinaSendWeibo(Stringtoken,Stringcontent)throwsException{ booleanflag=false; Timelinetimeline=newTimeline(); timeline.client.setToken(token); try { timeline.UpdateStatus(content); flag=true; } catch(WeiboExceptione) { flag=false; System.out.println(e.getErrorCode()); } returnflag; } publicstaticvoidmain(String[]args)throwsException { AccessTokenat=getToken("xxxx","xxx"); sinaSendWeibo(at.getAccessToken(),"测试呢"); } }
2)、腾迅
packageorg.utils; importjava.io.ByteArrayOutputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.OutputStream; importjava.io.UnsupportedEncodingException; importjava.security.MessageDigest; importjava.util.Scanner; importnet.sf.json.JSONObject; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.HttpClient; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.impl.client.DefaultHttpClient; importorg.apache.http.util.EntityUtils; importorg.core.weibo.tencent.api.UserAPI; importorg.core.weibo.tencent.oauthv2.OAuthV2; importorg.core.weibo.tencent.oauthv2.OAuthV2Client; /*** *腾迅自动登录并获取个人信息 *@authorzdw * */ publicclassTencent { publicstaticfinalStringHEXSTRING="0123456789ABCDEF"; publicstaticOAuthV2oAuth=newOAuthV2(); privatestaticHttpClientclient=newDefaultHttpClient(); //初始oAuth应用信息 publicstaticvoidinit(OAuthV2oAuth) { oAuth.setClientId("801216331"); oAuth.setClientSecret("ea71b26b0cbe5778cdd1c09ad17553a3"); oAuth.setRedirectUri("http://www.tencent.com/zh-cn/index.shtml"); } /** * *@paramqq *http://check.ptlogin2.qq.com/check?uin={0}&appid=15000101&r={1} *返回的第三个值 *@parampassword *QQ密码 *@paramverifycode *验证码 *@return加密后的密码 *@throwsUnsupportedEncodingException *@throwsException * */ publicstaticStringGetPassword(Stringqq,Stringpassword, Stringverifycode)throwsException { StringP=hexchar2bin(md5(password)); StringU=md5(P+hexchar2bin(qq.replace("\\x","").toUpperCase())); StringV=md5(U+verifycode.toUpperCase()); returnV; } publicstaticStringmd5(StringoriginalText)throwsException { bytebuf[]=originalText.getBytes("ISO-8859-1"); StringBufferhexString=newStringBuffer(); Stringresult=""; Stringdigit=""; try { MessageDigestalgorithm=MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(buf); byte[]digest=algorithm.digest(); for(inti=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(Exceptionex) { result=""; } returnresult.toUpperCase(); } publicstaticStringhexchar2bin(Stringmd5str)throwsUnsupportedEncodingException { ByteArrayOutputStreambaos=newByteArrayOutputStream(md5str.length()/2); for(inti=0;i<md5str.length();i=i+2) { baos.write((HEXSTRING.indexOf(md5str.charAt(i))<<4|HEXSTRING .indexOf(md5str.charAt(i+1)))); } returnnewString(baos.toByteArray(),"ISO-8859-1"); } /*** *模拟登录 *@paramqqQQ号码 *@parampasswordQQ密码 *@throwsException */ publicstaticvoidlogin(Stringqq,Stringpassword)throwsException { HttpGetget=newHttpGet("https://ssl.ptlogin2.qq.com/check?uin="+qq+"&appid=46000101&ptlang=2052&js_type=2&js_ver=10009&r=0.7948186025712065"); HttpResponseresponse=client.execute(get); Stringentity=EntityUtils.toString(response.getEntity()); String[]checkNum=entity.substring(entity.indexOf("(")+1,entity.lastIndexOf(")")).replace("'","").split(","); Stringpass=""; StringresponseData=""; //获取验证码(如果有验证码输出到C:/code.jpg,查看后输入可继续执行 if("1".equals(checkNum[0])) { //uin为qq号或者微博用户名 HttpGetgetimg=newHttpGet("http://captcha.qq.com/getimage?aid=46000101&r=0.3478789969909082&uin="+qq+"&vc_type="+checkNum[1]+""); HttpResponseresponse2=client.execute(getimg); OutputStreamos=newFileOutputStream("c:/code.jpg"); byte[]b=EntityUtils.toByteArray(response2.getEntity()); os.write(b,0,b.length); os.close(); Scannerin=newScanner(System.in); responseData=in.nextLine(); in.close(); } else { responseData=checkNum[1]; } /*********************加密密码***************************/ pass=GetPassword(checkNum[2],password,responseData); /*************************登录****************************/ HttpGetgetimg=newHttpGet("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"); HttpResponseresponse2=client.execute(getimg); HttpEntityhttpentity=response2.getEntity(); Stringentityxc=EntityUtils.toString(httpentity); System.out.println(entityxc); } /** * *请求微博开放平台应用返回登录授权页面,但是如果没有sessionKey的话永远登录不成功sessionKey *发现在返回的页面中一个input标签里放的url中有,所以要取到这个sessionKey其实直接访问标签中的url就可以跳转 * */ publicstaticStringgetUrl()throwsClientProtocolException,IOException { HttpGetgetcode=newHttpGet("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="); HttpResponseresponse3=client.execute(getcode); HttpEntityentityqqq=response3.getEntity(); Stringentityxcc=EntityUtils.toString(entityqqq); Stringform=entityxcc.substring(entityxcc.indexOf("<form"),entityxcc .indexOf("</form>")); String[]ss=form.split("/>"); Stringinput=""; for(inti=0;i<ss.length;i++) { if(ss[i].indexOf("name=\"u1\"")>0) { input=ss[i]; } ; } returninput.substring(input.indexOf("value=\"")+7,input.indexOf("\"type=\"")); } /** *解析并设置Token *@paramget *@throwsException */ publicstaticvoidsetToken(HttpGetget)throwsException { HttpResponseresponse4=client.execute(get); HttpEntityentityqqq1=response4.getEntity(); StringgetUrlcode=EntityUtils.toString(entityqqq1); //返回了最终跳转的页面URL,也就是回调页redirect_uri,页面地址上包含codeopenidopenkey //需要将这三个值单独取出来再拼接成code=xxxxx&openid=xxxxx&openkey=xxxxxx的形式 Stringentity=getUrlcode.substring(getUrlcode.indexOf("url="),getUrlcode.indexOf("\">")); StringBuffersb=newStringBuffer(); String[]arr=entity.split("\\?")[1].split("&"); for(intx=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); } /*** *调用(腾迅开放平台账户接口)获取一个人的信息 *@throwsException */ publicstaticvoidgetInfo()throwsException { //输出Token,如果拿到了Token就代表登录成功,并可以进行下一步操作。 System.out.println("Token="+oAuth.getAccessToken()); UserAPIgetuser=newUserAPI(oAuth.getOauthVersion()); StringuserJson=getuser.otherInfo(oAuth,"json","",oAuth.getOpenid()); JSONObjectuserJsonObject=JSONObject.fromObject(userJson); Integererrcode=(Integer)userJsonObject.get("errcode"); if(errcode==0) { JSONObjectuserdataJsonObject=(JSONObject)userJsonObject.get("data"); System.out.println(userdataJsonObject.toString()); } } publicstaticvoidmain(String[]args)throwsException { init(oAuth); login("123145","xxxx"); HttpGetget=newHttpGet(getUrl()); setToken(get); getInfo(); } }
4.发送成功都有对应的日志输出
新浪(最后一行日志):
2078DEBUG[2013-03-1416:35:29] {"created_at":"ThuMar1416:35:30+08002013","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:ヤ淡啶');查看个人信息成功后的日志标志:
QHttpClienthttpGet[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":..
日志未全列出,只是作为参考。
源码下载:http://xiazai.jb51.net/201607/yuanma/sinaAndTencent(jb51.net).rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。