Java simula Sina y Tencent inicia sesión automáticamente y envía funciones de Weibo a todos para su referencia. El contenido específico es el siguiente
1. Preparación
Simplemente inicie sesión sin solicitar la cuenta de desarrollador de Sina y Tencent. Si necesita enviar una función de Weibo, debe solicitar una cuenta de desarrollador de Sina y Tencent y agregar una aplicación de prueba.
Consulte el documento de ayuda oficial para el proceso. Dirección de la aplicación: Sina: http://open.weibo.com Tengxun: http://dev.t.qq.com/
Lo que necesitamos es la clave de aplicación, la aplicación Secre y Redirect_uri. El código fuente ya contiene la clave de prueba que solicité, pero debido a las restricciones, su cuenta no puede registrarse con éxito utilizando mi clave directamente.
2. cosas a tener en cuenta
1) Cabe señalar que la clave de aplicación de la aplicación, la aplicación Secre y Redirect_uri se encuentran en el archivo de configuración config.
client_id = 1745656892
Client_SerCret = 66056719C1D8CA7BCAF36F411217CEFA
redirect_uri = www.baidu.com
Dado que Redirect_uri solo se usa para las pruebas y no tiene una página de devolución de llamada directa, puede completar una dirección aquí, pero tenga cuidado de ser consistente con la "página de devolución de llamada" en la configuración de la aplicación advanced.
2) La cuenta de prueba en el código debe agregar la cuenta de prueba usted mismo. "Cuenta de prueba de información de aplicación de Sina; La "Lista blanca de creación de control de permiso de Tengxun". Por supuesto, también es posible usar la cuenta de desarrollador directamente.
3) Envíe a Weibo para citar Weibo4j-oauth2-beta2.1.1.1.zip de Sina y Java_SDK_V1.2.1.7z de Tengxun. La clase Core está debajo del paquete Util.
3. Código clave
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.HttpClient;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.httpmethodparams; import org.apache.http.httpexception; importar org.core.weibo.sina.oauth; import og.core.weibo.sina.timeline; importar org.core.weibo.http.cesstoken; import org.core.weibo.sina.model.weiboException; import org.core.weibo.sina.weibo4j.util.weiboconfig;/**** Simular el inicio de sesión automático y concurrente weibo* @author zdw**/public class siA {/**** Simular logine y obtener el token después de login* @param username* contraseña contraseña * @return * @throws httpexception * @throws ioexception */ public static accesstoken getToken (String UserName, String Password) lanza httpexception, ioexception {string clientId = weiboconfig.getValue ("client_id"); Cadena redirecturi = weiboconfig.getValue ("redirect_uri"); Cadena url = weiboconfig.getValue ("autorizeUrl"); Postmethod postmethod = new Postmetod (URL); // clave de aplicación postmethod.addparameter ("client_id", clientID); // página de redirección de la aplicación postmethod.addparameter ("redirect_uri", redirecturi); // Parámetros de inicio de sesión simulados // Desarrollador o prueba el nombre de usuario y la contraseña de la cuenta postmethod.addparameter ("UserId", UserName); postmethod.addparameter ("passwd", contraseña); postmethod.addparameter ("isloginsina", "0"); postmethod.addparameter ("acción", "enviar"); postmethod.addparameter ("Respuesta_Type", "Código"); Httpmethodparams param = postmethod.getParams (); param.setContentCharset ("UTF-8"); // Agregar lista de información de encabezado <WEADER> Headers = new ArrayList <WEADER> (); Headers.Add (nuevo encabezado ("Referente", "https://api.weibo.com/oauth2/authorize?client_id="+clientid+"&redirect_uri="+redirecturi+"&from=sina&response_type=code")); Headers.add (nuevo encabezado ("host", "api.weibo.com")); Headers.Add (nuevo encabezado ("agente de usuario", "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", encabezados); Client.executEmethod (postmetod); int status = postmethod.getStatUscode (); System.out.println (estado); if (status! = 302) {System.out.println ("Falló de actualización de token"); regresar nulo; } // Resolver el encabezado de token ubicación = postmethod.getResponseHeader ("ubicación"); if (ubicación! = null) {string returl = ubicación.getValue (); int begin = returl.IndexOf ("Code ="); if (begin! = -1) {int end = returl.IndexOf ("&", begin); if (end == -1) end = returl.length (); Código de cadena = returl.substring (begin + 5, end); if (code! = null) {oauth oauth = new Oauth (); intente {AccessToken token = oauth.getAccessTokenByCode (código); token de regreso; } catch (Exception e) {E.PrintStackTrace (); }}}} return null; } / ** * Enviar weibo * @param token certificado token * @param content weibo content * @return * @throws excepción * / public static boolean sinasendweibo (token de cadena, contenido de cadena) lanza excepción {boolean flag = false; Línea de tiempo timeline = new Timeline (); timeline.client.setToken (token); intente {timeline.updatestatus (contenido); bandera = verdadero; } catch (weiboException e) {flag = false; System.out.println (e.getErrorCode ()); } Bandera de retorno; } public static void main (string [] args) lanza la excepción {accessToken at = getToken ("xxxx", "xxx"); SINASENDWEIBO (at.getAccessToken (), "prueba"); }} 2) Tengxun
paquete org.utils; import java.io.bytearRayOutputStream; import java.io.fileOutputStream; import java.io.ioException; import java.io.outputstream; import java.io.unsupportedenCodingException; import java.ssses net.sf.json.jsonObject; import org.apache.http.httpentity; import org.apache.http.httpesponse; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.httpclient; importar; org.apache.http.client.methods.httpget; import org.apache.http.impl.client.defaulthttpclient; importar 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 inicia sesión automáticamente y obtiene información personal*@author zdw**/public Public static oauthv2 oauth = new Oauthv2 (); Cliente de httpClient privado estático = new DeFaUalThttpClient (); // información inicial de la aplicación OAuth Public static void init (OAuthv2 oauth) {oauth.setClientId ("801216331"); oauth.setClientSecret ("EA71B26B0CBE5778CDD1C09AD17553A3"); oauth.setedirecturi ("http://www.tencent.com/zh-cn/index.shtml"); }/** * * @param qq * http://check.ptlogin2.qq.com/check?uin= =0}&appid=15000101&r= =1} * El tercer valor devuelto * @param contraseña * qq contraseña * @@Param VerifyCode * VERIFICA String getPassword (string Qq, String Password, String VerifyCode) lanza la excepción {String P = HexChar2Bin (MD5 (Password)); Cadena u = md5 (p + hexchar2bin (qq.replace ("// x", "") .ToUpperCase ())); Cadena V = MD5 (U + VerifyCode.ToUpperCase ()); regreso v; } public static String MD5 (String OriginalText) lanza la excepción {byte buf [] = originalText.getBytes ("ISO-8859-1"); StringBuffer hexString = new StringBuffer (); Resultado de cadena = ""; Cadena digit = ""; Pruebe {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 (dígito); } resultado = hexString.ToString (); } catch (excepción ex) {result = ""; } return resultado.ToUpperCase (); } public static string hexchar2bin (String MD5Str) lanza UnsPportedEncodingException {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"); }/**** Simulationic inicio de sesión* @param qq qq número* @param contraseña qq contraseña* @throws excepción*/public static void login (string qq, string contraseña) lanza la excepción {httpget get = nueva httpget ("https://ssl.ptlogin2.qq.com/check?uin=" + qq + "& appid = 46000101 & ptlang = 2052 & js_type = 2 & js_ver = 10009 & r = 0.7948186025712065"); HttpResponse respuesta = client.execute (get); String entity = entityUtils.ToString (respuesta.getEntity ()); String [] checkNum = entity.substring (entity.IndexOf ("(") + 1, entity.lastIndexOf (")")). Reemplazar ("'", "") .split (","); String pass = ""; Cadena Responsedata = ""; // Obtenga el código de verificación (si hay una salida del código de verificación a c: /code.jpg, ingrese y continúe ejecutando if ("1" .equals (checknum [0]))) {// uin es un número QQ o nombre de usuario weibo httpget getiMg = nuevo Httpget ("http://captcha.qq.com/getimage?aid=46000101&r=0.3478789999909082&uin=" + qq + "& vc_type =" + checknum [1] + ""); HttpResponse Response2 = Client.execute (getImg); OutputStream OS = nuevo FileOutputStream ("c: /code.jpg"); byte [] b = entityUtils.tobytearray (respuesta2.getEntity ()); OS.Write (B, 0, B.Length); os.close (); Escáner en = nuevo escáner (System.in); ResponseData = in.NextLine (); cercar(); } else {ResponseData = checkNum [1]; } / ** ************************ /** ****************************************** *******************************/httpget "& Aid = 46000101 & Target = top & u1 = https%3a%2fopen.t.qq.com%2fcgi-bin%2foauth2%2fauthorize%3fclient_id%3d"+ oauth.getClientid ()+ "%26Response_Type%3dcode%26RedirectiCt. oauth.getedirecturi ()+ "& 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 & 2 & js_ver = 10009"); HttpResponse Response2 = Client.execute (getImg); Httpentity httpentity = respuesta2.getEntity (); String entityXc = entityUtils.toString (httpentity); System.out.println (EntityXC); } /** * * Solicite la aplicación de la plataforma Weibo Open para volver a la página de autorización de inicio de sesión, pero si no hay Key Session Key, el inicio de sesión nunca tendrá éxito. SessionKey se encuentra en la URL colocada en una etiqueta de entrada en la página devuelta, por lo que debe obtener esta Key Session. De hecho, puede acceder directamente a la URL en la etiqueta y saltar */public static string getUrl () lanza ClientProtocoleException, ioException {httpget getCode = new httpget ("https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id="+ oAuth.getClientId ()+) ()+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)++)+)+)+)+)+)+)+)+)+)+) "& Response_Type = Code & Redirect_uri =" + oauth.getedirecturi () + "& checkStatus = yes & appFrom = & g_tk & checktype = showauth & state ="); HttpResponse Response3 = Client.execute (getCode); Httpentity entityqqq = respuesta3.getEntity (); String entityXcc = entityUtils.toString (entityqqq); String form = entityXcc.substring (entityXcc.indexof ("<form"), entityxcc .indexof ("</form>")); Cadena [] 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 y establecer token * @param get * @throws excepción */public static void setToken (httpget get) se lanza excepción {htttPonsespone = respuesta4.getEntity (); 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 ("código")> = 0 || arr [x] .indexof ("openID")> = 0 || arr [x] .indexof ("openkey")> = 0) {sb.append (arr [x]+"&"); }; } // Use el código para obtener accesstoken oauthv2client.parseauthorization (sb.substring (0, sb.length () - 1), oauth); oauth.setGrantType ("Authorize_code"); Oauthv2client.accessToken (Oauth); } /**** Llame (interfaz de la plataforma Open Open de Tengxun) para obtener la información de una persona* @throws Exception* /public static void getInfo () lanza la excepción {// emite el token. Si obtiene el token, significa que el inicio de sesión es exitoso y puede realizar la próxima operación. 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 ("datos"); System.out.println (userDataJsonObject.ToString ()); }} public static void main (string [] args) lanza la excepción {init (oauth); inicio de sesión ("123145", "xxxx"); Httpget get = new httpget (getUrl ()); Setkoken (Get); getInfo (); }} 4. Habrá una salida de registro correspondiente al enviar correctamente
Sina (Última línea de registro):
2078 DEBUG [2013-03-14 16:35:29] {"creado_at": "Thu 14 de marzo 16:35:30 +0800 2013 "," ID ": 35557911329499940," Mid ":" 35557911329499940 "," idstr ":" 35557911329499940 "," texto ":" prueba "," fuente ":" ...
Teng Xun:
Bandera de registro para inicio de sesión exitoso:
ptuicb ('0', '0', 'https: //open.t.qq.com/cgi-bin/oauth2/authorize? client_id = 801216331 & respuesta_type = code & redirect_uri = http:', '1' ',' logine con éxito! ',' ㄗ s: ヤ Dani ');
QhttpClient httpget [3] respuesta = {"data": {"birth_day": 26, "birth_month": 8, "birth_year": 2011, "city_code": "2", "comp": null, "country_code": "1", "edu": null, "correo electrónico": "," exp ": 141, fansnum:" ":"
Los registros no figuran en su totalidad, pero son solo de referencia.
Descarga del código fuente: http://xiazai.vevb.com/201607/yuanma/sinaandtencent(vevb.com).rar
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.