Java는 Sina와 Tencent를 자동으로 로그인하고 참조를 위해 Weibo 기능을 모든 사람에게 보냅니다. 특정 내용은 다음과 같습니다
1. 준비
Sina 및 Tencent의 개발자 계정을 신청하지 않고 로그인하십시오. Weibo 기능을 보내야하는 경우 Sina 및 Tencent의 개발자 계정을 신청하고 테스트 응용 프로그램을 추가해야합니다.
프로세스에 대한 공식 도움말 문서를 참조하십시오. 응용 프로그램 주소 : Sina : http://open.weibo.com Tengxun : http://dev.t.qq.com/
우리가 필요로하는 것은 앱 키, 앱 비밀 및 redirect_uri입니다. 소스 코드에는 이미 신청 한 테스트 키가 포함되어 있지만 제한으로 인해 내 키를 직접 사용하여 계정을 기록 할 수 없습니다.
2. 주목할만한 것들
1) 응용 프로그램의 앱 키, 앱 비밀 및 redirect_uri는 프로젝트의 루트 디렉토리의 해당 구성 구성 파일에 있습니다.
client_id = 1745656892
Client_Sercret = 66056719C1D8CA7BCAF36F411217CEFA
redirect_uri = www.baidu.com
redirect_uri는 테스트에만 사용되며 직접 콜백 페이지가 없으므로 여기에서 주소를 작성할 수 있지만 응용 프로그램에 대한 혜택 설정에서 "콜백 페이지"와 일치하도록주의하십시오.
2) 코드의 테스트 계정은 테스트 계정을 직접 추가해야합니다. Sina의 "응용 프로그램 정보 테스트 계정"; Tengxun의 "권한 제어 제작 화이트리스트". 물론 개발자 계정을 직접 사용할 수도 있습니다.
3) weibo를 인용하여 Sina의 Weibo4j-Oauth2-Beta2.1.zip 및 Tengxun의 Java_SDK_V1.2.1.7Z를 인용하십시오. 핵심 클래스는 UTIL 패키지 아래에 있습니다.
3. 키 코드
1)시나
패키지 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.htpclient org.apache.commons.httpclient.params.httpmethodparams; import org.apache.http.httpexception; import org.core.weibo.sina.oauth; import org.core.weibo.sina.toletline; import org.core.weibo.sina.http.accestoken; org.core.weibo.sina.model.weiboexception; import org.core.weibo.sina.weibo4j.util.weiboconfig;/**** Simulate 자동 로그인 및 동시 Weibo* @author zdw*/public class sina {/**** 로그인* @param tersern* @param tersern* @param tersern 암호 비밀번호 * @return * @throws httpexception * @throws ioexception */ public static accesstoken getToken (문자열 사용자 이름, 문자열 암호) httpexception, ioException {String clientId = wiboconfig.getValue ( "client_id"); String redirecturi = weiboconfig.getValue ( "redirect_uri"); 문자열 url = weiboconfig.getValue ( "authorizeUrl"); postmethod postMethod = new postMethod (url); // 앱 키 postMethod.addParameter ( "client_id", clientId); // 앱의 리디렉션 페이지 postMethod.addParameter ( "redirect_uri", redirecturi); // MOCK 로그인 매개 변수 // 개발자 또는 테스트 계정 사용자 이름 및 비밀번호 postMethod.addParameter ( "userId", username); postmethod.addparameter ( "passwd", password); postmethod.addparameter ( "Isloginsina", "0"); postmethod.addparameter ( "action", "제출"); 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+"&from=sina&response_type=code")); headers.add (새 헤더 ( "호스트", "api.weibo.com"); headers.add (새 헤더 ( "사용자 에이전트", "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", 헤더); client.executemethod (postmethod); int status = postMethod.getStatusCode (); System.out.println (상태); if (status! = 302) {system.out.println ( "토큰 새로 고 실패"); 널 리턴; } // 토큰 헤더 위치를 해결합니다. 위치 = postMethod.getResponseHeader ( "location"); if (location! = null) {String returl = location.getValue (); int begin = returl.indexof ( "code ="); if (시작! = -1) {int end = returl.indexof ( "&", 시작); if (end == -1) end = returl.length (); 문자열 코드 = returl.substring (시작 + 5, 끝); if (code! = null) {oauth oauth = new Oauth (); try {accesstoken token = oauth.getAccessTokenByCode (코드); 복귀 토큰; } catch (예외 e) {e.printstacktrace (); }}}} return null; } / ** * weibo * @param 토큰 인증 토큰을 보내십시오 * @param content weibo content * @return * @throws 예외 * / public static boolean sinasendweibo (문자열 토큰, 문자열 내용) 예외 {boolean flag = false; 타임 라인 타임 라인 = 새로운 타임 라인 (); timeline.client.settoken (토큰); try {timeline.updatestatus (content); flag = true; } catch (weiboException e) {flag = false; System.out.println (e.geterRorCode ()); } 반환 플래그; } public static void main (string [] args)은 예외 {accesstoken at = gettoken ( "xxxx", "xxx"); sinasendweibo (at.getAccessToken (), "test"); }} 2) Tengxun
패키지 org.utils; import java.io.bytearrayoutputStream; import java.io.fileoutputStream; import java.io.ioexception; import java.io.outputStream; import java.io.unsupportedEncodexception; import java.security.messagegedigest; java.util.scanner; 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; 수입 org.apache.http.client.methods.httpget; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.util.entityutils; import org.core.wibo.tencent.api.userapi; import org.core.weibo.tencent.oauthv2.oauthv2; import org.core.weibo.tencent.oauthv2.oauthv2client;/****tengxun을 자동으로 로그인하고 개인 정보를 얻는다*@author zdw**/public class tencent {public final string hexstring = "0123456899; public static oauthv2 oauth = 새로운 oauthv2 (); 개인 정적 httpclient client = new defaulthttpclient (); // 초기 OAUTH 응용 프로그램 정보 공개 정적 무효 Init (OAUTHV2 OAUTH) {OAUTH.SETCLIENDID ( "801216331"); OAUTH.SETCLIENTECRET ( "EA71B26B0CBE5778CDD1C09AD17553A3"); Oauth.setredirecturi ( "http://www.tencent.com/zh-cn/index.shtml"); }/** * * @param qq * http://check.ptlogin2.qq.com/check?uin= {0 }&appid=15000101&r= {1} * 세 번째 값 리턴 * @Param Password * QQ Password * @param verifycode * @return pesspell 정적 문자열 getPassword (문자열 QQ, 문자열 암호, 문자열 verifyCode)는 예외 {문자열 p = hexchar2bin (md5 (password)); 문자열 u = md5 (p + hexchar2bin (qq.replace ( "// x", "") .toupperCase ()); 문자열 v = md5 (u + verifycode.toupperCase ()); 반환 v; } public static string md5 (String OriginalText) 예외 {byte buf [] = ordigintext.getBytes ( "iso-8859-1"); StringBuffer hexstring = new StringBuffer (); 문자열 결과 = ""; 문자열 digit = ""; try {messageDigest 알고리즘 = messageDigest.getInstance ( "MD5"); algorithm.reset (); algorithm.update (buf); 바이트 [] 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 (숫자); } result = hexstring.toString (); } catch (예외) {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 (md5str.charat (i)) << 4 | hexstring .indexof (md5str.charat (i + 1))); } 새 문자열을 반환합니다 (baos.tobytearRay (), "ISO-8859-1"); }/**** 시뮬레이션 로그인* @param qq qq 번호* @param password qq password* @throws exception*/public static void login (문자열 qq, 문자열 비밀번호) 예외 {httpget get = new httpget ( "https://ssl.ptlogin2.qqq.com/check?uin=" + qq + "& appid = 46000101 & ptlang = 2052 & js_type = 2 & js_ver = 10009 & r = 0.7948186025712065"); httpresponse response = client.execute (get); 문자열 entity = entityutils.toString (response.getEntity ()); 문자열 [] checknum = entity.substring (entity.indexof ( "("( "("( "(")) + 1, "))"). 대체 ( " '", "") .split ( ","); 문자열 pass = ""; String responseData = ""; // 확인 코드를 가져옵니다 (C : /code.jpg에 검증 코드 출력이있는 경우 입력하고 if ( "1".Equals (CheckNum [0]))) {uin은 QQ 번호 또는 Weibo 사용자 이름 httpget getImg = new입니다. httpget ( "http://captcha.qq.com/getimage?aid=46000101&r=0.3478787899969909082&uin=" + qq + "& vc_type =" + checknum [1] + "); httpresponse response2 = client.execute (getimg); outputStream os = 새 FileOutputStream ( "c : /code.jpg"); 바이트 [] b = entityutils.tobytearray (response2.getentity ()); os.write (b, 0, b.length); os.close (); SCANNER IN = NEW SCANNER (System.In); responseData = in.nextline (); 넣다(); } else {responseData = checknum [1]; } /** ************************ Encryption password******************************* */ pass = GetPassword(checkNum[2], password, responseData); /** ****************************** 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 ()+ "%26Response_type%3dcode%26REDIRECT ="+ 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 (); 문자열 entityxc = entityutils.tostring (httpentity); System.out.println (entityxc); } /** * * 로그인 인증 페이지로 돌아가려면 Weibo Open 플랫폼 애플리케이션을 요청하지만 SessionKey가없는 경우 로그인은 성공하지 못합니다. SessionKey는 반환 된 페이지의 입력 태그에 배치 된 URL에서 발견 되므로이 SessionKey를 가져와야합니다. 실제로 태그에서 URL에 직접 액세스 할 수 있으며 */public static string geturl ()는 clientProtoColexception, ioExcepte {httpget getCode = new httpget ( "https://open.t.qq.com/cgi-bin/oauth2/authorize? "& response_type = code & redirect_uri =" + oauth.getRedirectUri () + "& checkStatus = 예 & appfrom = & g_tk & checktype = showauth & state ="); httpresponse response3 = client.execute (getCode); httpentity entityqqq = response3.getentity (); 문자열 entityxcc = entityutils.toString (entityqqq); 문자열 form = entityxcc.substring (entityxcc.indexof ( "<form"), entityxcc .indexof ( "</form>")); 문자열 [] ss = form.split ( "/>"); 문자열 입력 = ""; 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 */public static void settoken (httpget get) 예외 (httprest resonge); entityqqq1 = response4.getentity (); code = xxxxx & openid = xxxxx & openkey = xxxxxxx string entity = geturlcode.substring (geturlcode.indexof ( "url ="), geturlcode.indexof ( "/"> ")); StringBuffer sb = new StringBuffer (); 문자열 [] 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]+"); }; } // 코드를 사용하여 AccessToken Oauthv2Client.parseauthorization (sb.substring (0, sb.length () -1), oauth); oauth.setgranttype ( "authorize_code"); OAUTHV2CLIENT.ACCESSTOKE (OAUTH); } /**** 전화 (tengxun 오픈 플랫폼 계정 인터페이스)를 호출하려면 사람의 정보를 얻으려면* @throws 예외* /public static void getInfo () 예외 {// 토큰을 출력합니다. 토큰을 받으면 로그인이 성공하고 다음 작업을 수행 할 수 있음을 의미합니다. 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); 정수 errcode = (정수) userjsonobject.get ( "errcode"); if (errcode == 0) {jsonObject userDataJsonObject = (jsonObject) userJsonObject.get ( "data"); System.out.println (userDataJsonObject.toString ()); }} public static void main (String [] args)은 예외 {init (oauth); 로그인 ( "123145", "xxxx"); httpget get = new httpget (geturl ()); 정착 (get); getInfo (); }} 4. 성공적으로 보낼 때 해당 로그 출력이 있습니다.
Sina (마지막 로그 라인) :
2078 디버그 [2013-03-14 16:35:29] { "create_at": "Thu 3 월 16:35:30 +0800 2013 ","ID ": 3555791132949940,"MID ":"3555791132949940 ","idstr ":"3555791132949940 ","텍스트 ":"테스트 ","소스 ":"...
Teng Xun :
성공적인 로그인을위한 로그 플래그 :
ptuicb ( '0', '0', 'https : //open.t.qq.com/cgi-bin/oauth2/authorize? client_id = 801216331 & response_type = code & redirect_uri = http :', '1', ''login success!
qhttpclient httpget [3] response = { "data": { "birth_day": 26, "birth_month": 8, "birth_year": 2011, "city_code": "2", "comp": "country_code": "1", "edu": "이메일": "": "141," "": "
로그는 전체적으로 나열되지 않지만 참조용입니다.
소스 코드 다운로드 : http://xiazai.vevb.com/201607/yuanma/sinaandtencent(Vevb.com).rar
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.