Java simule Sina et Tencent se connecter automatiquement et envoie des fonctions Weibo à tout le monde pour votre référence. Le contenu spécifique est le suivant
1. Préparation
Connectez-vous simplement sans demander le compte de développeur de Sina et Tencent. Si vous devez envoyer une fonction Weibo, vous devez demander un compte de développeur SINA et Tencent et ajouter une application de test.
Veuillez vous référer au document d'aide officiel pour le processus. Adresse de l'application: sina: http://open.weibo.com Tengxun: http://dev.t.qq.com/
Ce dont nous avons besoin, c'est de la clé d'application, de l'application Secre et Redirect_uri. Le code source contient déjà la clé de test pour laquelle j'ai postulé, mais en raison de restrictions, votre compte ne peut pas être connecté à utiliser directement ma clé directement.
2. Choses à noter
1) Il convient de noter que la clé d'application de l'application, l'application secre et redirect_uri se trouvent dans le fichier de configuration config.properties correspondant dans le répertoire racine du projet.
client_id = 1745656892
client_sercret = 66056719c1d8ca7bcaf36f411217cefa
redirect_uri = www.baidu.com
Étant donné que Redirect_uri n'est utilisé que pour les tests et n'a pas de page de rappel directe, vous pouvez simplement remplir une adresse ici, mais veillez à être cohérent avec la "page de rappel" dans les paramètres avancés par l'application.
2) Le compte de test dans le code doit ajouter le compte de test vous-même. Le "compte d'information-test de l'application" de SINA; La "liste blanche de la liste blanche" de Tengxun. Bien sûr, il est également possible d'utiliser directement le compte du développeur.
3) Envoyez Weibo pour citer le weibo4j-oauth2-beta2.1.1.1.zip et Tengxun de Tengxun. La classe de base est sous le package Util.
3. Code clé
1) Sina
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.Methods.PostModoD; 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. org.core.weibo.sina.model.weiboexception; import org.core.weibo.sina.weibo4j.util.weiboconfig; / *** * simule le connexion automatique et simultanément weibo * @Author zdw * * / public class @Param Username * @Parmed anermin et @ParaMing Usaim et @Para mot de passe mot de passe * @return * @throws httpexception * @throws ioException * / public static AccessToken getToken (String Username, String Motway) lève httpexception, ioException {String clientId = weiBoConFig.getValue ("client_id"); String redirectturi = weiboconfig.getValue ("redirect_uri"); String url = weiboconfig.getValue ("AuthorizeUrl"); PostMethod PostMethod = new PostMethod (URL); // application key postMethod.AddParameter ("client_id", clientId); // la page Redirection de l'application postMethod.AddParameter ("redirect_uri", redirectUri); // Mock Login Paramètres // Développeur ou test de test Nom d'utilisateur et mot de passe postMethod.AddParameter ("utilisateur", nom d'utilisateur); PostMethod.AddParameter ("Passwd", mot de passe); PostMethod.AddParameter ("Isloginsina", "0"); PostMethod.AddParameter ("Action", "Soumider"); postMethod.AddParameter ("Response_Type", "code"); HttpMethodParams param = postMethod.getParams (); param.setContentCharset ("UTF-8"); // Ajouter une liste d'informations d'en-tête <en-tête> en-têtes = new ArrayList <Sider> (); headers.add (nouvel en-tête ("référer", "https://api.weibo.com/oauth2/authorize?client_id="+Clientid+"&redirect_uri="+redirereri+"&from=sina&response_type=code")); header.add (nouvel en-tête ("hôte", "api.weibo.com")); en-têtes.add (nouvel en-tête ("utilisateur-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", en-têtes); client.executeMethod (postMethod); int status = postMethod.getStaturScode (); System.out.println (statut); if (status! = 302) {System.out.println ("Token Refresh a échoué"); retourner null; } // Résoudre l'emplacement de l'en-tête de jeton = postMethod.getResponseHeader ("emplacement"); if (emplacement! = null) {String returl = location.getValue (); int début = returl.indexof ("code ="); if (begin! = -1) {int end = returl.indexof ("&", begin); if (end == -1) end = returl.length (); String Code = RETUTL.SUBSTRING (Begin + 5, end); if (code! = null) {oAuth oAuth = new oAuth (); Try {AccessToken Token = oAuth.getAccessTokenBycode (code); Token de retour; } catch (exception e) {e.printStackTrace (); }}}} return null; } / ** * Envoyer Weibo * @Param Token Certified Token * @Param Content Weibo Content * @return * @throws exception * / public static boolean sinasendweibo (String token, String Content) lève exception {boolean flag = false; Timeline timeline = new timeline (); timeline.client.setToken (jeton); essayez {timeline.updateStatus (contenu); Flag = true; } catch (WeiboException e) {Flag = false; System.out.println (e.getErrorCode ()); } drapeau de retour; } public static void main (String [] args) lève une exception {AccessToken at = getToken ("xxxx", "xxx"); sinasendweibo (at.getAccessToken (), "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.unsupportedEncodingException; import java.security.mesagedigest; import java.utitil.scanner; import; net.sf.json.jsonObject; import org.apache.http.httpentity; import org.apache.http.httpreson; import org.apache.http.client.httpclient; 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; / *** * Tengxun se connecte automatiquement et obtient des informations personnelles * @author zdw * * / public classe Tencent {public static static hexstring = "0123456789aBCDDDD"; public static oauthv2 oAuth = new oAuthv2 (); Client httpClient statique privé = new defaulthTTPClient (); // Informations d'application OAuth initiales publiques static void init (oAuthv2 oAuth) {oAuth.setClientid ("801216331"); oAuth.SetClientimentSecret ("EA71B26B0CBE5778CDD1C09AD17553A3"); oauth.setRedirerecturi ("http://www.tencent.com/zh-cn/index.shtml"); } / ** * * @param qq * http://check.ptlogin2.qq.com/check?uin= {0 }&appid=15000101&r={1} * La troisième valeur renvoyée * @param mot de passe * QQ Passue * @param VerifyCode * Verification Code * @rern Encrypted Motway * String getPassword (String QQ, String Motword, String VerifyCode) lève l'exception {String p = hexChar2Bin (md5 (mot de passe)); String u = md5 (p + hexchar2bin (qq.replace ("// x", "") .toupperase ())); String v = md5 (u + VerifyCode.ToupperCase ()); retour v; } public static String MD5 (String OriginalText) lève une exception {Byte buf [] = originalText.getBytes ("ISO-8859-1"); StringBuffer hexString = new StringBuffer (); Résultat de chaîne = ""; String Digit = ""; essayez {MessagediGest algorithm = MessagediGest.getInstance ("md5"); Algorithm.Reset (); Algorithm.Update (BUF); octet [] 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 (chiffre); } result = hexstring.toString (); } catch (exception ex) {result = ""; } return result.touppercase (); } public static String hexChar2bin (String md5str) lève unportdencodingException {bytearrayoutputStream baos = new bytearrayoutputStream (md5str.length () / 2); pour (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"); } / *** * Login de simulation * @param QQ QQ Number * @param mot de passe QQ Mot de passe * @throws Exception * / public static void Login (String Qq, String Motway) lève une 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.Exécute (get); String Entity = EntityUtils.ToString (Response.GetEntity ()); String [] checkNum = entity.substring (entity.indexof ("(") + 1, entity.lastIndexof (")")). Remplace ("'", "") .split (","); String pass = ""; String ResponseData = ""; // Obtenez le code de vérification (s'il y a une sortie de code de vérification sur c: /code.jpg, entrez-le et continuez à exécuter if ("1" .equal Httpget ("http://captcha.qq.com/getimage?aid=46000101&r=0.3478789969909082&uin=" + qq + "& vc_type =" + checkNum [1] + ""); HttpResponse Response2 = client.Exécute (getImg); OutputStream os = new FileOutputStream ("c: /code.jpg"); BYTE [] B = EntityUtils.ToByTearray (Response2.getEntity ()); OS.Write (B, 0, B.Length); os.close (); Scanner dans = nouveau scanner (System.in); ResponseData = in.NextLine (); joindre(); } else {répondata = checknum [1]; } / ** *********************. /** ****************************** Login****************************** */ 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% 2fopen.t.qq.com% 2fcgi-bin% 2foAuth2% 2fauthorize% 3fclient_id% 3d" + oauth.getClientId () + "% 26RAPONDE_TYPE% 3DCODE% 26redIrct_uri =" + oAuth.getRedirereCturi () + "& pTreDirect = 1 & h = 1 & from_ui = 1 & dumy = & qlogin_param = abbfew = ddd & wring =% e6% 8e% 88% e6% 9d% 83 & fp = loginerRororert & Action = 8-13-240977 & g = 1 & t = 1 & dmmy = & js_type = 2 & js_ver = 1"); HttpResponse Response2 = client.Exécute (getImg); Httpentity httpentity = réponse2.getEntity (); String entityXc = entityUtils.toString (httpentity); System.out.println (EntityXc); } / ** * * Demande l'application de plate-forme ouverte Weibo pour revenir à la page d'autorisation de connexion, mais s'il n'y a pas de sessionky, la connexion ne réussira jamais. SessionKey se trouve dans l'URL placée dans une balise d'entrée dans la page retournée, vous devez donc obtenir ce SessionKey. En fait, vous pouvez accéder directement à l'URL dans la balise et à sauter * / public static String getUrl () lève clientProtoCoLexception, ioException {httpget getCode = new httpget ("https://open.t.qq.com/cgi-bin/oauth2/Authorize?client_id=" + oaTh.getClid () + + "& Response_Type = Code & redirect_uri =" + oauth.getRedirerecturi () + "& Checkstatus = Oui & AppFrom = & g_tk & CheckType = showAuth & State ="); HttpResponse Response3 = client.Exécute (getCode); Httpentity entityqqq = réponse3.getEntity (); String entityXcc = entityUtils.toString (entityqqq); String Form = EntityXccc.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 = /" "));} / ** * Parse and Set Token * @param get get * @throws exception * / public static stat = réponse4 String Entity = getUrlCode.substring (getUrlCode.indexof ("url ="), getUrlCode.indexof ("/"> ")); StringBuffer sb = new StringBuffer (); String [] arr = entity.split ("//?") [1] .split ("&"); pour (int x = 0; x <arr.length; x ++) {if (arr [x] .Indexof ("code")> = 0 || arr [x] .Indexof ("openId")> = 0 || arr [x] .Indexof ("openKey")> = 0) {sb.apprend (arr [x] + "&"); }; } // Utiliser le code pour obtenir AccessToken oAuthv2Client.ParsautAutorisation (SB.SubString (0, sb.length () - 1), oAuth); oAuth.setgrantType ("Authorize_code"); OAuthv2Client.AccessToken (OAuth); } / *** * Appelez (interface de compte Tengxun Open Platform) pour obtenir les informations d'une personne * @throws exception * / public static void getInfo () lève une exception {// Sortir le jeton. Si vous obtenez le jeton, cela signifie que la connexion est réussie et que vous pouvez effectuer la prochaine opération. 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) lève une exception {init (oAuth); Login ("123145", "xxxx"); Httpget get = new httpget (getUrl ()); Établissement (obtenir); getInfo (); }} 4. Il y aura la sortie du journal correspondant lors de l'envoi avec succès
Sina (dernière ligne de journal):
2078 DEBUG [2013-03-14 16:35:29] {"Created_at": "jeu 14 mars 16:35:30 +0800 2013 "," id ": 3555791132949940," mid ":" 3555791132949940 "," idstr ":" 355579113294940 "," texte ":" test "," source ":" ...
Teng Xun:
Indicateur de journal pour la connexion réussie:
PTUICB ('0', '0', 'https: //open.t.qq.com/cgi-bin/oauth2/authorize? Client_id = 801216331 & Response_Type = Code & redirect_uri = http:', '1', 'Logging Informly!', 'ㄗ ㄗ s: ヤ Dani');
QhttpClient httpget [3] réponse = {"data": {"naissance_day": 26, "naissance_month": 8, "naissance_year": 2011, "city_code": "2", "comp": null, "country_code": "1", "edu": null, "e-mail": "," exp ": 141," fansnum ":.:"
Les journaux ne sont pas répertoriés dans leur intégralité, mais sont pour référence uniquement.
Téléchargement du code source: http://xiazai.vevb.com/201607/yuanma/sinaandtencent(vevb.com).rar
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.