Java mensimulasikan Sina dan Tencent secara otomatis masuk dan mengirimkan fungsi Weibo kepada semua orang untuk referensi Anda. Konten spesifiknya adalah sebagai berikut
1. Persiapan
Cukup masuk tanpa melamar akun pengembang Sina dan Tencent. Jika Anda perlu mengirim fungsi Weibo, Anda perlu mengajukan permohonan untuk akun pengembang SINA dan Tencent dan menambahkan aplikasi pengujian.
Silakan merujuk ke dokumen bantuan resmi untuk prosesnya. Alamat aplikasi: SINA: http://open.weibo.com Tengxun: http://dev.t.qq.com/
Yang kami butuhkan adalah kunci aplikasi, App Secre dan Redirect_uri. Kode sumber sudah berisi kunci pengujian yang saya terapkan, tetapi karena pembatasan, akun Anda tidak dapat masuk dengan sukses menggunakan kunci saya secara langsung.
2. Hal -hal yang perlu diperhatikan
1) Perlu dicatat bahwa kunci aplikasi aplikasi, App Secre dan Redirect_uri berada di file konfigurasi config.properties yang sesuai di direktori root proyek.
client_id = 1745656892
client_sercret = 66056719c1d8ca7bcaf36f411217Cefa
redirect_uri = www.baidu.com
Karena Redirect_uri hanya digunakan untuk pengujian dan tidak memiliki halaman panggilan balik langsung, Anda dapat mengisi alamat di sini, tetapi berhati-hatilah untuk konsisten dengan "halaman panggilan balik" di pengaturan aplikasi-advanced.
2) Akun pengujian dalam kode perlu menambahkan akun tes sendiri. "Akun Tes Informasi Aplikasi" SINA; Tengxun "Izin Kontrol-Buat Whitelist" Tengxun. Tentu saja, dimungkinkan juga untuk menggunakan akun pengembang secara langsung.
3) Kirim Weibo untuk mengutip Weibo4j-oauth2-beta2.1.1.zip dan java_sdk_v1.2.7z dari Tengxun. Kelas inti berada di bawah paket util.
3. Kode Kunci
1) Sina
Paket org.utils; import java.io.ioException; import java.util.arraylist; import java.util.list; import org.apache.commons.httpclient.header; impor org.apache.commons.httpclient.httpclient; impor; org.apache.commons.httpclient.methods.postmethod; impor org.apache.commons.httpclient.params.httpmethodparams; impor org.apache.htintp.htpexception; impor org.core.weibo.sina.oAuth; org.core.weibo.sina.http.accesstoken; impor org.core.weibo.sina.model.weiboException; Impor org.core.weibo.sina.weibo4j.util.weiboconfig;/**** mensimulasikan loin otomatis dan concurrent weibo {concurrent {/weibo* Masuk dan dapatkan token setelah login * @param nama pengguna nama pengguna * @param kata sandi * @return * @throws httpException * @throws ioException */ public accessToken getToken (string username, string password) melempar httpException, ioException {string clientid = weiboceid. String redirectur = weiboconfig.getValue ("redirect_uri"); String url = weiboconfig.getValue ("otorizeUrl"); PostMethod PostMethod = New PostMethod (URL); // Kunci Aplikasi PostMethod.AddParameter ("Client_id", ClientId); // halaman pengalihan aplikasi postmethod.addparameter ("redirect_uri", redirectur); // parameter login tiruan // pengembang atau uji nama pengguna dan kata sandi postmethod.addparameter ("userid", nama pengguna); postmethod.addparameter ("passwd", kata sandi); postmethod.addparameter ("Isloginsina", "0"); postmethod.addparameter ("aksi", "kirim"); postmethod.addparameter ("response_type", "code"); Httpmethodparams param = postmethod.getParams (); param.setContentCharset ("UTF-8"); // Tambahkan daftar informasi header <Header> header = ArrayList baru <Header> (); headers.add (header baru ("referer", "https://api.weibo.com/oauth2/authorize?client_id="+ClientId+"&Redirect_uri="+Redirectur+"&from=sina&response_type=code")); headers.add (header baru ("host", "api.weibo.com")); headers.add (header baru ("agen pengguna", "mozilla/5.0 (Windows NT 6.1; RV: 11.0) Gecko/20100101 Firefox/11.0")); Httpclient client = httpclient baru (); client.getHostConfiguration (). getParams (). setParameter ("http.default-headers", header); client.executemethod (postmethod); status int = postmethod.getStatusCode (); System.out.println (status); if (status! = 302) {System.out.println ("Token Refresh Gagal"); kembali nol; } // Selesaikan lokasi header token = postmethod.getResponseader ("lokasi"); 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 (); Kode string = returl.substring (mulai + 5, end); if (kode! = null) {oauth oauth = oAuth baru (); coba {accessToken token = oauth.getAccessTokenByCode (kode); Token kembali; } catch (Exception e) {E.PrintStackTrace (); }}}} return null; } / ** * Kirim weibo * @param token token bersertifikat * @param konten weibo konten * @return * @throws Exception * / public static boolean sinasendweibo (string token, konten string) melempar pengecualian {boolean flag = false; Timeline Timeline = Timeline baru (); timeline.client.settoken (token); coba {timeline.updatestatus (konten); bendera = true; } catch (weiboException e) {flag = false; System.out.println (e.getErrorCode ()); } mengembalikan bendera; } public static void main (string [] args) melempar Exception {accessToken at = gettoken ("xxxx", "xxx"); sinasendweibo (at.getAccessToken (), "tes"); }} 2) Tengxun
Paket org.utils; impor java.io.bytearrayoutputStream; impor java.io.fileoutputStream; import java.io.ioException; impor java.io.outputStream; import java.io.unsupportedencodingException; impor java.security.messrageragegest; net.sf.json.jsonObject; import org.apache.http.httpentity; import org.apache.http.httpresponse; impor org.apache.http.client.clientprotocolexception; impor org.apache.htp.client.clientprotocception; Impor 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; org.core.weibo.tencent.oauthv2.oAuthv2; impor org.core.weibo.tencent.oauthv2.oauthv2client;/****tengxun secara otomatis masuk dan memperoleh informasi pribadi*@Author zdw**/kelas publik tencent {Perserangan Statis Publik Static Static Perseras Statis Public Static STATIC PUBLIK STATIC PUBLIC STATIC PUBLIC STATIC PUBLIC = OAuthv2 statis publik oAuth = oauthv2 baru (); klien httpclient private statis = defaulthttpclient baru (); // Informasi Aplikasi OAuth Awal Public Static Void Init (OAuthv2 OAuth) {OAuth.SetClientID ("801216331"); oauth.setClientSecret ("EA71B26B0CBE5778CDD1C09AD17553A3"); oauth.setredirectur ("http://www.tencent.com/zh-cn/index.shtml"); } /** * * @param qq * http://check.ptlogin2.qq.com/check?uin={0}&appid=15000101&r={1 } * The third value returned* @param password * QQ password* @param verifycode * Verification code* @return Encrypted password* @throws UnsupportedEncodingException * @throws Exception * */ public string statis getPassword (string qq, kata sandi string, string verifyCode) melempar pengecualian {string p = hexchar2bin (md5 (kata sandi)); String u = md5 (p + hexchar2bin (qq.replace ("// x", "") .touppercase ())); String v = md5 (u + verifyCode.touppercase ()); mengembalikan v; } public static string md5 (string originalText) melempar Exception {byte buf [] = originalText.getBytes ("iso-8859-1"); StringBuffer hexString = new StringBuffer (); Hasil string = ""; String digit = ""; Coba {MessageDigest Algorithm = MessageSpetest.getInstance ("md5"); algorithm.reset (); Algorithm.update (BUF); byte [] digest = algorithm.digest (); untuk (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 (Exception ex) {result = ""; } return result.touppercase (); } public static String hexChar2bin (String md5str) melempar UnsupportedEncodingException {ByTeArrayOutputStream Baos = new ByTeArrayOutputStream (md5str.length () / 2); untuk (int i = 0; i <md5str.length (); i = i + 2) {baos.write ((hexString.indexof (md5str.charat (i)) << 4 | hexstring .indexof (md5str.charat (i + 1))))); } return string baru (Baos.TobyTeArray (), "ISO-8859-1"); }/**** Login simulasi* @param qq qq nomor* @param kata sandi qq kata sandi* @throws Exception*/public static void login (string qq, string password) melempar pengecualian {httpget get = httpget baru ("https://ssl.ptlogin2.qq.check?ceck? "& appID = 46000101 & ptlang = 2052 & js_type = 2 & js_ver = 10009 & r = 0,7948186025712065"); Httpresponse response = client.execute (get); String entitas = entityutils.toString (response.getEntity ()); String [] checknum = entity.substring (entity.indexOf ("(") + 1, entity.lastIndexOf (")"). Ganti ("'", "") .split (","); String pass = ""; String responseData = ""; // Dapatkan kode verifikasi (jika ada output kode verifikasi ke c: /code.jpg, masukkan dan terus jalankan jika ("1" .Equals (checknum [0]))) {// UIN adalah nomor qq atau nama pengguna Weibo httpget getimg = baru Httpget ("http://captcha.qq.com/getimage?aid=46000101&r=0.3478789969909082&uin=" + qq + "& vc_type =" + checknum [1] + ""); Httpresponse response2 = client.execute (getImg); OutputStream os = new fileoutputStream ("c: /code.jpg"); byte [] b = entityutils.tobytearray (response2.getEntity ()); os.write (b, 0, b.length); os.close (); Pemindai di = pemindai baru (System.in); responseData = in.nextline (); melampirkan(); } else {responseData = checknum [1]; } / ** ********************** A Enkripsi Kata Sandi ****************************** / pass = getPassword (checknum [2], kata sandi, responedata); /** ****************************** Login *****************************/httpget getImg = httpget baru ("https://ssl.ptlogin2.qq.com/login?ptloS=205&su="+ qq+ "/qqq. "&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.getRedirectur ()+ "& ptredirect = 1 & h = 1 & from_ui = 1 & dumy = & qlogin_param = abbfew = ddd & wording =%e6%8e%88%E6%9d%83 & fp = Loginerrorort & Action = 8-13-240977 & g = 1 & t = dumon = dumon = 8-13-24097 & g = 1 & t = 1 & t = Httpresponse response2 = client.execute (getImg); Httpentity httpentity = response2.getEntity (); String entityxc = entityutils.toString (httpentity); System.out.println (EntityXC); } /** * * Meminta aplikasi platform Weibo Open untuk kembali ke halaman otorisasi login, tetapi jika tidak ada sesi, login tidak akan pernah berhasil. SessionKey ditemukan di URL yang ditempatkan di tag input di halaman yang dikembalikan, jadi Anda perlu mendapatkan Sesi ini. Faktanya, Anda dapat secara langsung mengakses URL dalam tag dan lompat */string statis public getUrl () melempar ClientProtocolException, ioException {httpget getSode = httpget baru ("https://open.t.qq.com/cgi-nin/oauth2/Authorize?client. "& response_type = kode & redirect_uri =" + oAuth.getRedirectur () + "& checkstatus = Ya & appfrom = & g_tk & checkType = showAuth & state ="); Httpresponse response3 = client.execute (getCode); Httpentity entityqqq = response3.getEntity (); String entityxcc = entityutils.toString (entityqqq); String form = entityxcc.substring (entityxcc.indexof ("<form"), entityxcc .indexof ("</form>")); String [] ss = form.split ("/>"); String input = ""; untuk (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 * @throws Exception */ public static void setToken(HttpGet get) throws Exception { HttpResponse response4 = client.execute(get); HttpEntity Entityqqq1 = response4.getEntity (); kode = xxxxx & openId = xxxxx & openkey = xxxxxxx string entitas = getUrlCode.substring (getUrlCode.indexof ("url ="), getUrlCode.indexof ("/"> ")); StringBuffer SB = StringBuffer baru (); String [] arr = entity.split ("//?") [1] .split ("&"); untuk (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] "&" & "); }; } // Gunakan kode untuk mendapatkan AccessToken OAuthv2Client.Parseauthorization (SB.SubString (0, SB.Length () - 1), OAuth); oauth.setGrantType ("otorize_code"); Oauthv2client.accesstoken (oauth); } /**** Panggilan (antarmuka akun platform terbuka Tengxun) untuk mendapatkan informasi seseorang* @throws Exception* /public static void getInfo () melempar pengecualian {// keluaran token. Jika Anda mendapatkan token, itu berarti login berhasil dan Anda dapat melakukan operasi berikutnya. System.out.println ("token ="+oauth.getAccessToken ()); Userapi getUser = UserApi baru (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) melempar Exception {init (oAuth); login ("123145", "xxxx"); Httpget get = httpget baru (getUrl ()); Settoken (dapatkan); getInfo (); }} 4. Akan ada output log yang sesuai saat mengirim
SINA (Baris terakhir log):
2078 DEBUG [2013-03-14 16:35:29] {"create_at": "Kamis 14 Mar 16:35:30 +0800 2013 "," id ": 3555791132949940," mid ":" 3555791132949940 "," idstr ":" 3555791132949940 "," Teks ":" Tes "," Sumber ":" ...
Teng Xun:
Bendera log untuk login yang berhasil:
ptuicb ('0', '0', 'https: //open.t.qq.com/cgi-bin/oauth2/authorize? client_id = 801216331 & response_type = Code & redirect_uri = http:', '1', 'Loin berhasil!', '
QHTTPClient httpget [3] respons = {"data": {"lahir_day": 26, "lahir_month": 8, "lahir_year": 2011, "city_code": "2", "comp": null, "country_code": "1", "edu": nol, "email": "", ":": ":" 1 "," 1 "," edu ": edu:
Log tidak terdaftar secara lengkap, tetapi hanya untuk referensi.
Unduh Kode Sumber: http://xiazai.vevb.com/201607/yuanma/sinaandtencent(vevb.com).rar
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.