JavaはSinaとTencentをシミュレートし、自動的にログインし、参照のためにWeibo関数を全員に送信します。特定のコンテンツは次のとおりです
1。準備
SinaとTencentの開発者アカウントを申請せずにログインするだけです。 Weibo機能を送信する必要がある場合は、Sina and Tencentの開発者アカウントを申請してテストアプリケーションを追加する必要があります。
プロセスの公式ヘルプ文書を参照してください。アプリケーションアドレス:SINA:http://open.weibo.com tengxun:http://dev.t.qq.com/
必要なのは、Appキー、App Secre、Redirect_uriです。ソースコードには既に適用されたテストキーが含まれていますが、制限のため、アカウントを私のキーを直接使用して正常にログインすることはできません。
2。注意すべきこと
1)アプリケーションのAPPキー、App secre、およびredirect_uriは、プロジェクトのルートディレクトリの対応するconfig.properties configurationファイルにあることに注意してください。
client_id = 1745656892
client_sercret = 66056719c1d8ca7bcaf36f411217cefa
Redirect_uri = www.baidu.com
Redirect_uriはテストにのみ使用されており、直接コールバックページがないため、ここでアドレスに入力するだけですが、アプリケーションが適用される設定の「コールバックページ」と一致するように注意してください。
2)コード内のテストアカウントは、テストアカウントを自分で追加する必要があります。 SINAの「アプリケーション情報テストアカウント」。 Tengxunの「許可コントロール - 作成ホワイトリスト」。もちろん、開発者アカウントを直接使用することもできます。
3)Weiboを送信して、SinaのWeibo4J-Oauth2-Beta2.1.1.1.zipとTengxunの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; org.apach.commons.httpcl org.apache.commons.httpclient.params.httpmethodparams; Import org.apache.http.httpexception; Import org.core.weibo.sina.outh; Import org.core.weibo.sina.sina.timeline; import org.core.core.core.core.core.core.core.core.weibo.sina.chedtped org.core.weibo.sina.model.weiboexception; Import org.core.weibo.weibo4j.util.weiboconfig;/****自動ログインと同時weibo* @author zdw**/public class sina {/*******パスワード * @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); // mock loginパラメーター//開発者またはテストアカウントユーザー名とパスワード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"); //ヘッダー情報リスト<header> headers = new ArrayList <Header>(); headers.add(new Header( "参照者"、 "https://api.weibo.com/oauth2/authorize?client_id="+clientid+"&redirect_uri="+ redirecturi+」 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 refreshed"); nullを返します。 } //トークンヘッダーの場所を解決します= 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();文字列code = returl.substring(begin + 5、end); if(code!= null){oauth oauth = new oauth(); try {AccessToken token = oauth.getAccessTokenByCode(code);トークンを返します。 } catch(Exception e){e.printstacktrace(); }}}} nullを返します。 } / ** * weiboを送信 * @paramトークン認定トークン * @paramコンテンツweiboコンテンツ * @return * @throws例外 * / public static boolean sinasendweibo(string token、string content)throws exception {boolean flag = false;タイムラインタイムライン= new Timeline(); Timeline.client.settoken(token); {Timeline.updateStatus(content); flag = true; } catch(weiboexception e){flag = false; System.out.println(e.getErrorCode()); } flagを返します。 } public static void main(string [] args)throws exception {accesstoken at = gettoken( "xxxx"、 "xxx"); sinasendweibo(at.getaccestoken()、 "test"); }} 2)Tengxun
Package org.utils; import java.io.bytearrayoutputstream; Import java.io.fileoutputStream; Import java.io.ioexception; Import java.io.outputStream; Import java.io.unsupportedencodingception; 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; 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.api.api; Import; org.core.weibo.tencent.oauthv2.oauthv2; Import org.core.weibo.tencent.oauthv2.oauthv2client;/****tengxunは個人情報を自動的にログインして取得します*@author zdw**/public final sintic hextring = "01256 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.qqc.com/check?uin= {0}&appid = 15000101&r= {1} * @paramパスワード * qqパスワード * @param verifycode * recipation * @return * @Return * static string getPassword(String QQ、String Password、String VerifyCode)スロー例外{String P = HexChar2Bin(MD5(Password)); string u = md5(p + hexchar2bin(qq.replace( "// x"、 "").touppercase()));文字列v = md5(u + verifycode.touppercase()); vを返します。 } public static string md5(string originaltext)スロー例外{byte buf [] = originalText.getBytes( "ISO-8859-1"); stringbuffer hexstring = new StringBuffer();文字列結果= "";文字列digit = ""; try {MessageDigest algorithm = MessagedGest.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(例外ex){result = ""; } return result.touppercase(); } public static string hexchar2bin(string md5str)unsupportedencodingexception {bytearrayoutputstream baos = new bytearrayoutputstream(md5str.length() / 2); for(int i = 0; i <md5str.length(); i = i + 2){baos.write((hexstring.indexof(i))<< 4 | hexstring .indexof(md5str.charat(i + 1)))); } new String(baos.tobytearray()、 "ISO-8859-1"); }/****シミュレーションログイン* @param qq qq qq qq number* @param password qq password* @throws例外*/public static void login(string qq、string password)shlews {https://ssl.ptlogin2.cc.com/check?uin= " + qq + "&appid = 46000101&ptlang = 2052&js_type = 2&js_ver = 10009&r = 0.7948186025712065"); httpresponse応答= client.execute(get); string entity = entityutils.toString(respons.getEntity()); string [] checknum = entity.substring(entity.indexof( "(") + 1、entity.lastindexof( ")"))。文字列pass = "";文字列responsedata = ""; //検証コードを取得します(C:/code.jpgに検証コード出力がある場合、それを入力して、if( "1" .equals(checknum [0])))){// uinはqq番号またはweibo username httpget getimg = new httpget( "http://captcha.qc.com/getimage?aid=46000101&r = 0.347878996990909082&uin=" + qq + "&vc_type =" + checknum [1] + ""); httpresponse response2 = client.execute(getimg); outputStream os = new fileoutputStream( "c:/code.jpg"); byte [] b = entityutils.tobytearray(respons2.getentity()); os.write(b、0、b.length); os.close();スキャナーin = new Scanner(system.in); responsedata = in.nextline(); in.close(); } else {ressionedata = checknum [1]; } / ** ************************************************************* / pass = getPassword(checknum [2]、パスワード、ressuntedata); /*********************************************************************************/httpget getimg = new httpget( "https://ssl.ptlogin2.qq.com/login?ptlang=2052&u ="+ qq+ "+ qq+"+ "+"+ "&Aid = 46000101&Target = Top&U1 = https%3a%2fopen.t.qq.com%2fcgi-bin%2foauth2%2fauthorize%3fclient_id%3d"+ oauth.getclientid()+ "+"%26Response_tepe%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); } /** * * weiboオープンプラットフォームアプリケーションを要求して、ログイン認証ページに戻りますが、sessionkeyがない場合、ログインは成功しません。 SessionKeyは、返されたページの入力タグに配置されたURLにありますので、このsessionKeyを取得する必要があります。実際、タグのURLに直接アクセスでき、ジャンプ */public static string getUrl()throws clientProtoColexception、ioException {httpget getCode = new httpget( " "&Response_type = code&redirect_uri =" + oauth.getRedirecturi() + "&checkStatus = yes&appfrom =&g_tk&checktype = showauth&state ="); httpresponse response3 = client.execute(getCode); httpentity entityqqq = respons.getEntity(); string entityxcc = entityutils.toString(entityqqq); string form = entityxcc.substring(entityxcc.indexof( "<form")、entityxcc .indexof( "</form>")); string [] ss = form.split( "/>");文字列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例外 */public static void setoken(httpget get)throws excest4 = client response4 = client response4 = client response4 = client response4 = client response4 = client respones Response4.getEntity(); string geturlcode = entityutils.tostring(entityqq1); 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]+"); }; } //コードを使用して、アクセスしたoauthv2client.parseuthorization(sb.substring(0、sb.length()-1)、oauth)を取得します。 oauth.setgranttype( "Authorize_code"); oauthv2client.accesstoken(oauth); } /**** call(tengxun openプラットフォームアカウントインターフェイス)に個人の情報を取得する* @throws例外* /public static void getInfo()throws Exception {//トークンを出力します。トークンを取得した場合、ログインが成功し、次の操作を実行できることを意味します。 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()); setoken(get); getInfo(); }} 4.正常に送信すると、対応するログ出力があります
Sina(ログの最後の行):
2078デバッグ[2013-03-14 16:35:29] {"created_at": "Thu 3月16:35:30 +0800 2013 "、" id ":355791132949940、" mid ":" 355791132949940 "、" idstr ":" 355579113294940 "、" Text ":" Test "、" source ":" ...
Teng Xun:
ログインを成功させるためのログフラグ:
ptuicb( '0'、 '0' ''、 'https://open.t.qc.com/cgi-bin/oauth2/authorize?client_id = 801216331&response_type = code&redirect_uri = http:'、 '' 1 '
qhttpclient httpget [3] response = {"data":{"birth_day":26、 "birth_month":8、 "birth_year":2011、 "city_code": "2"、 "comp":null、 "country_code": "1"、 "edu":null、 "": "
ログは完全にリストされていませんが、参照用のみです。
ソースコードのダウンロード:http://xiazai.vevb.com/201607/yuanma/sinaandtencent(vevb.com).rar
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。