Java simula Sina e Tencent login automaticamente e envia funções do Weibo a todos para sua referência. O conteúdo específico é o seguinte
1. Preparação
Basta fazer login sem se candidatar à conta do desenvolvedor da Sina e da Tencent. Se você precisar enviar uma função Weibo, precisará solicitar uma conta de desenvolvedor da Sina e da Tencent e adicionar um aplicativo de teste.
Consulte o documento oficial de ajuda para o processo. Endereço do aplicativo: Sina: http://open.weibo.com Tengxun: http://dev.t.qq.com/
O que precisamos é a chave do aplicativo, o aplicativo secre e redirect_uri. O código -fonte já contém a chave de teste que solicitei, mas devido a restrições, sua conta não pode ser registrada usando com êxito minha chave diretamente.
2. Coisas para observar
1) Deve -se notar que a chave do aplicativo do aplicativo, o aplicativo Secre e Redirect_uri estão no arquivo de configuração Config.Properties correspondente no diretório raiz do projeto.
client_id = 1745656892
client_sercret = 66056719C1D8CA7BCAF36F411217CEFA
Redirect_uri = www.baidu.com
Como Redirect_uri é usado apenas para teste e não possui uma página de retorno de chamada direta, você pode apenas preencher um endereço aqui, mas tenha cuidado para ser consistente com a "página de retorno de chamada" nas configurações de advancência do aplicativo.
2) A conta de teste no código precisa adicionar a conta de teste você mesmo. "Conta de teste de informação do aplicativo" do Sina; A lista de permissões de controle de controle de Tengxun ". Obviamente, também é possível usar a conta do desenvolvedor diretamente.
3) Envie o Weibo para citar o Weibo4j-OATH2-BETA2.1.1.1.ZIP e Java_SDK_V1.2.1.7z de Tengxun. A classe principal está no pacote Util.
3. Código da chave
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; importar org.apache.http.httpexception; importar org.core.weibo.sina.oauth; import org.core.weibo.ina.timeline; import ousut.core.core.core.core.ceibe.core.weibo.ina.temeline; import.oauth; org.core.weibo.sina.model.weiboException; importar org.core.weibo.sina.weibo4j.util.weiboconfig;/**** Simulate o login automático e o weibo* @author*/public*/Public Class Sina-) Nome de usuário * @param Senha senha * @return * @THOWS HTTPEXCECCETO * @THOWSOWSCECCECTION */ Public Static AccessToken GetToken (Nome de usuário da String, String senha) lança httPexception, ioexception {String clientId = weiboconfig.getValue ("client_id"); String redirecturi = weiboconfig.getValue ("redirect_uri"); String url = weiboconfig.getValue ("autorizeurl"); Pós -metódico postmethod = novo PostMethod (URL); // chave de aplicativo postmethod.addparameter ("client_id", clientId); // Página de redirecionamento do aplicativo postmethod.addparameter ("redirect_uri", redirecturi); // Mock Parâmetros de login // Desenvolvedor ou conta de teste Nome de usuário e senha postmethod.addparameter ("UserID", nome de usuário); postmethod.addparameter ("passwd", senha); postmethod.addparameter ("isloginsina", "0"); postmethod.addparameter ("ação", "submeter"); postmethod.addparameter ("Response_type", "Code"); HttpMethodParams param = PostMethod.getParams (); param.setContentCharset ("UTF-8"); // Adicione a lista de informações do cabeçalho <Heparel> cabeçalhos = novo ArrayList <Hewewer> (); headers.add (novo cabeçalho ("referente", "https://api.weibo.com/oauth2/authorize?client_id="+clientid+"&redirect_uri="+redirecturi+"&from=sina&roponse_type=code=code"); headers.add (novo cabeçalho ("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")); Cliente httpclient = new httpClient (); client.gethostConfiguration (). getParams (). SetParameter ("http.default-headers", cabeçalhos); client.Executemethod (Postmethod); int status = postmethod.getStatuscode (); System.out.println (status); if (status! = 302) {System.out.println ("Token Refresh falhou"); retornar nulo; } // Resolva a localização do cabeçalho do token = PostMethod.GetResponseHeader ("Localização"); if (location! = null) {string Returl = location.getValue (); int Begin = Returl.indexOf ("code ="); if (comece! if (end == -1) end = Returl.Length (); Código da String = Returl.Substring (Begin + 5, End); if (code! = null) {oauth oauth = new oauth (); tente {accessToken token = oauth.getAccessTokenByCode (código); Token de retorno; } catch (Exceção e) {e.printStackTrace (); }}}} retornar nulo; } / ** * Enviar weibo * @param token token certificado * @param Conteúdo conteúdo weibo * @return * @throws Exceção * / public estático boolean sinasendweibo (string token, conteúdo da string) lança exceção {boolean sinalizador = false; Linha do tempo da linha do tempo = new Timeline (); timeline.client.setToken (token); tente {timeline.updatestatus (content); bandeira = true; } catch (weiBoException e) {sinalizador = false; System.out.println (e.getErrorCode ()); } retornar sinalizador; } public static void main (string [] args) lança exceção {accessToken at = getToken ("xxxx", "xxx"); Sinasendweibo (at.getAccessToken (), "teste"); }} 2) Tengxun
pacote org.utils; importar java.io.byteArrayoutputStream; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.outputStream; importanan.io.ionsupportEncodingException; import.ilil.ilmengest; importangest; importestes; importEstern; importestesningest; importEstern; importesten.mSedGest; Importent.milvAngest; Importent.milvAgest; net.sf.json.jsonObject; importar org.apache.http.httpentity; importar org.apache.http.httpropnse; importar org.apache.http.client.clientProtoToToxception; importância org.apache.http.client.httpclent; org.apache.http.client.methods.httpget; importar org.apache.http.impl.client.defaulthttpclient; importar org.apache.http.util.entityutils ;mterg.core.webo.tencente.aPiAPIPI; org.core.weibo.tencent.oauthv2.oauthv2; importar org.core.weibo.tencent.oauthv2.oauthv2client;/****tengxun registra automaticamente e obtém informações pessoais. public static outhv2 oauth = novo oauthv2 (); cliente estático privado httpclient = new DefaultTtpClient (); // Informações iniciais do aplicativo OAuth public static void init (OAuthv2 oauth) {oauth.setClientId ("801216331"); OAuth.SetClientSecret ("EA71B26B0CBE5778CDD1C09AD17553A3"); OAuth.SetRredirecturi ("http://www.tencent.com/zh-cn/index.shtml"); }/** * * @param qq * http://check.ptlogin2.qq.com/check?uin= {0a }&appid=15000101&r= {1} * o terceiro valor retornado * @param senha * qq senha * @paramcode * código de verificação * @returCeExtTtedtedted * String getPassword (string qq, string senha, string verifyCode) lança a exceção {string p = hexchar2bin (md5 (senha)); String u = md5 (p + hexchar2bin (qq.replace ("// x", "") .touppercase ())); String v = md5 (u + verifyCode.ToupPercase ()); retornar v; } public static string md5 (string originaltext) lança a exceção {byte buf [] = originaltext.getBytes ("ISO-8859-1"); StringBuffer hexstring = new StringBuffer (); String result = ""; String Digit = ""; tente {Messagedigest algorithm = Messagedigest.getInstance ("md5"); algorithm.reset (); Algorithm.Update (BUF); byte [] DIGEST = ALGORITHM.DIGEST (); for (int i = 0; i <diger.length; i ++) {digit = Integer.toHexString (0xff & diGest [i]); if (digit.Length () == 1) {Digit = "0" + Digit; } hexstring.append (dígito); } resultado = hexstring.toString (); } catch (Exceção ex) {resultado = ""; } return result.touppercase (); } public static string hexchar2bin (string md5str) lança UnsupportEdEncodingException {byteArrayOutputStream baos = novo bytearrayOutputStream (md5str.length () / 2); para (int i = 0; i <md5str.Length (); i = i + 2) {Baos.write ((hexstring.indexof (md5str.charat (i)) << 4 | hexstring .IndexOf (md5st.charat (i + 1))); } Return New String (baos.tobytearray (), "ISO-8859-1"); }/**** Login de simulação* @param qq Número qq* @param Senha qq Senha* @Throws Exceção*/public static void Login (string qq, string senha) lança exceção {httpget get = new httpget ("https://ssl.ptlogin2.qqq.com/check?guin=" "& Appid = 46000101 & ptlang = 2052 & js_type = 2 & js_ver = 10009 & r = 0,7948186025712065"); HTTPRESPOnsion Response = client.execute (get); String entity = entityutils.toString (Response.getEntity ()); String [] checknum = entity.substring (entity.indexof ("(") + 1, entity.lastIndexOf (")"))). Substituir ("'", "") .split (","); String pass = ""; String Respoedata = ""; // Obtenha o código de verificação (se houver um código de verificação em saída para c: /code.jpg, insira -o e continue executando se ("1" .equals (checknum [0]))) {// uin é um número QQ ou nome de usuário weibo httpget getImg = novo Httpget ("http://captcha.qq.com/getImage?aid=46000101&r=0.34778789969909082&uin=" + qq + "& vc_type =" + checknum [1] + ""); HttpResponse resposta2 = client.execute (getImg); OutputStream OS = new FileOutputStream ("c: /code.jpg"); byte [] b = entityutils.tobytearray (resposta2.getEntity ()); OS.WRITE (B, 0, B.Length); os.close (); Scanner in = new Scanner (System.in); responseData = in.nextLine (); in.Close (); } else {Respoedata = checknum [1]; } / ** ************************ Senha de criptografia ******************************* /** **************************** LOGIN ********************* "&aid=46000101&target=top&u1=https%3A%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 & Whording =%e6%8e%88%e6%9d 83 & fp = loginerrorert & Action = 8-13-240977 & g = 1 & t = 1 & t = 1 & t = 1 & t = 1 & t = 1 & t = 1 & s = 1 & rameRerrorert & 8-13-240977 & g = 1 & t = 1 & t = 1 & 1 &" HttpResponse resposta2 = client.execute (getImg); Httpentity httpentity = resposta2.getEntity (); String entityxc = entityutils.toString (httpentity); System.out.println (entityxc); } /** * * Solicite o aplicativo Weibo Open Platform para retornar à página de autorização de login, mas se não houver sessão, o login nunca será bem -sucedido. A sessão de sessões é encontrada no URL colocado em uma tag de entrada na página devolvida, então você precisa obter essa sessão. De fato, você pode acessar diretamente o URL na tag e saltar */public static string geturl () lança clientprotocolexception, ioexception {httpget getCode = new httpget ("https://open.t.qq.com/cgi--bin/oauth2/authorize?client_idgen" " "& Response_type = código & redirect_uri =" + oauth.getredirecturi () + "& checkStatus = sim & appFrom = & g_tk & checkType = showauth & state ="); HTTPRESPOnsion Response3 = client.execute (getCode); Httpentity entityqqq = resposta3.getEntity (); String entityxcc = entityutils.toString (entityqqq); String form = entityxcc.substring (entityxcc.indexof ("<form"), entityxcc .Indexof ("</morm>")); String [] ss = form.split ("/>"); String input = ""; para (int i = 0; i <ss.length; i ++) {if (ss [i] .IndexOf ("nome =/" u1/"")> 0) {input = ss [i]; }; } retornar input.substring (input.indexOf ("value =/" ") + 7, input.indexof ("/"type =/" ""));}/** * analisar e definir token * @param get * @throws excepção */public static void SettOnke (httgEgget) (exceção get * httSpRows */httRows */public static void SettOnke (httgEtgEt) (exceção httTtStRows * entityqqq1 = resposta4.getentity (); código = xxxxxx & openId = xxxxx & openKey = xxxxxxxxx string entity = geturlcode.substring (geturlcode.indexof ("url ="), geturlcode.indexof ("/"> "); StringBuffer sb = new StringBuffer (); String [] arr = entity.split ("//?") [1] .split ("&"); para (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]+""; }; } // Use o código para obter o AccessToken OAuthv2Client.ParseAuthorization (sb.substring (0, sb.length () - 1), oauth); oauth.setGrantType ("Authorize_code"); Oauthv2client.accessToken (OAuth); } /**** CHAMADA (interface da conta da plataforma aberta Tengxun) para obter informações de uma pessoa* @THOWSECT Exceção* /public static void getinfo () lança exceção {// em saída o token. Se você receber o token, isso significa que o login será bem -sucedido e você pode executar a próxima operação. System.out.println ("token ="+oauth.getAccessToken ()); UserApi getUser = novo userApi (oauth.getoauthversion ()); String userjson = getUser.otherinfo (oauth, "json", "", oauth.getOpenid ()); JsonObject userjsonObject = jsonObject.FromObject (userjson); Inteiro errcode = (Inteiro) userjsonObject.get ("errcode"); if (errcode == 0) {jsonObject userDatajsonObject = (jsonObject) userjsonObject.get ("data"); System.out.println (userDatajsonObject.toString ()); }} public static void main (string [] args) lança exceção {init (oauth); login ("123145", "xxxx"); Httpget get = new httpget (geturl ()); Settoken (Get); getinfo (); }} 4. Haverá saída de log correspondente ao enviar com sucesso
Sina (última linha de log):
2078 Debug [2013-03-14 16:35:29] {"Created_at": "Qui 14 de março 16:35:30 +0800 2013 "," ID ": 3555791132949940," MID ":" 3555791132949940 "," idstr ":" 3555791132949940 "," texto ":" teste, "fonte": "..." ... ...
Teng Xun:
Bandeira do log para login bem -sucedido:
ptuicb ('0', '0', 'https: //open.t.qq.com/cgi-bin/oauth2/authorize? client_id = 801216331 & resposta_type = code & redirect_uri = htp:', '1', 'login com sucesso!
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":..
Os logs não estão listados na íntegra, mas são apenas para referência.
Download do código -fonte: http://xiazai.vevb.com/201607/yuanma/sinaandtencent(vevb.com).rar
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.