Java simulates Sina and Tencent automatically login and sends Weibo functions to everyone for your reference. The specific content is as follows
1. Preparation
Just log in without applying for Sina and Tencent’s developer account. If you need to send a Weibo function, you need to apply for a Sina and Tencent’s developer account and add a test application.
Please refer to the official help document for the process. Application address: Sina: http://open.weibo.com Tengxun: http://dev.t.qq.com/
What we need is the App Key, App Secre and redirect_URI. The source code already contains the test key I applied for, but due to restrictions, your account cannot be logged in successfully using my key directly.
2. Things to note
1) It should be noted that the application's App Key, App Secre and redirect_URI are in the corresponding config.properties configuration file in the root directory of the project.
client_ID=1745656892
client_SERCRET=66056719c1d8ca7bcaf36f411217cefa
redirect_URI=www.baidu.com
Since redirect_URI is only used for testing and does not have a direct callback page, you can just fill in an address here, but be careful to be consistent with the "callback page" in the application-advanced settings.
2) The test account in the code needs to add the test account yourself. Sina's "Application Information-Test Account"; Tengxun's "Permission Control-Create Whitelist". Of course, it is also possible to use the developer account directly.
3) Send Weibo to quote Sina's weibo4j-oauth2-beta2.1.1.zip and Tengxun's Java_SDK_v1.2.1.7z. The core class is under the Util package.
3. Key Code
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;import org.core.weibo.sina.Oauth;import org.core.weibo.sina.Timeline;import org.core.weibo.sina.http.AccessToken;import org.core.weibo.sina.model.WeiboException;import org.core.weibo.sina.weibo4j.util.WeiboConfig;/*** * Simulate automatic login and concurrent Weibo* @author zdw * */public class Sina { /*** * Simulate login and get the token after login * @param username Username * @param password Password * @return * @throws HttpException * @throws IOException */ public static AccessToken getToken(String username,String password) throws HttpException, IOException { String clientId = WeiboConfig.getValue("client_ID"); String redirectURI = WeiboConfig.getValue("redirect_URI"); String url = WeiboConfig.getValue("authorizeURL"); PostMethod postMethod = new PostMethod(url); //App Key postMethod.addParameter("client_id",clientId); //App's redirect page postMethod.addParameter("redirect_uri",redirectURI); //Mock login parameters//Developer or test account username and password postMethod.addParameter("userId", username); postMethod.addParameter("passwd", password); postMethod.addParameter("isLoginSina", "0"); postMethod.addParameter("action", "submit"); postMethod.addParameter("response_type","code"); HttpMethodParams param = postMethod.getParams(); param.setContentCharset("UTF-8"); //Add header information List<Header> headers = new ArrayList<Header>(); headers.add(new Header("Referer", "https://api.weibo.com/oauth2/authorize?client_id="+clientId+"&redirect_uri="+redirectURI+"&from=sina&response_type=code")); headers.add(new Header("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")); HttpClient client = new HttpClient(); client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); client.executeMethod(postMethod); int status = postMethod.getStatusCode(); System.out.println(status); if (status != 302) { System.out.println("token refresh failed"); return null; } //Resolve Token Header location = postMethod.getResponseHeader("Location"); 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(); String code = retUrl.substring(begin + 5, end); if (code != null) { Oauth oauth = new Oauth(); try{ AccessToken token = oauth.getAccessTokenByCode(code); return token; }catch(Exception e){ e.printStackTrace(); } } } } return null; } /** * Send Weibo* @param token Certified Token * @param content Weibo content* @return * @throws Exception */ public static boolean sinaSendWeibo(String token,String content) throws Exception { boolean flag = false ; Timeline timeline = new Timeline(); timeline.client.setToken(token); try { timeline.UpdateStatus(content); flag = true ; } catch (WeiboException e) { flag = false ; System.out.println(e.getErrorCode()); } return flag; } public static void main(String[] args) throws 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.MessageDigest;import java.util.Scanner;import 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;import 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 automatically logs in and obtains personal information* @author zdw * */public class Tencent{ public static final String HEXSTRING = "0123456789ABCDEF"; public static OAuthV2 oAuth = new OAuthV2(); private static HttpClient client = new DefaultHttpClient(); // initial oAuth application information public static void init(OAuthV2 oAuth) { oAuth.setClientId("801216331"); oAuth.setClientSecret("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 } * The third value returned* @param password * QQ password* @param verifycode * Verification code* @return Encrypted password* @throws UnsupportedEncodingException * @throws Exception * */ public static String GetPassword(String qq, String password, String verifycode) throws Exception { String P = hexchar2bin(md5(password)); String U = md5(P + hexchar2bin(qq.replace("//x", "").toUpperCase())); String V = md5(U + verifycode.toUpperCase()); return V; } public static String md5(String originalText) throws Exception { byte buf[] = originalText.getBytes("ISO-8859-1"); StringBuffer hexString = new StringBuffer(); String result = ""; String digit = ""; try { 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(digit); } result = hexString.toString(); } catch (Exception ex) { result = ""; } return result.toUpperCase(); } public static String hexchar2bin(String md5str) throws 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)))); } return new String(baos.toByteArray(), "ISO-8859-1"); } /*** * Simulation login* @param qq QQ number* @param password QQ password* @throws Exception */ public static void login(String qq, String password) throws 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.execute(get); String entity = EntityUtils.toString(response.getEntity()); String[] checkNum = entity.substring(entity.indexOf("(") + 1,entity.lastIndexOf(")")).replace("'", "").split(","); String pass = ""; String responseData = ""; // Get the verification code (if there is a verification code output to C:/code.jpg, enter it and continue to execute if ("1".equals(checkNum[0]))) { // Uin is a qq number or Weibo username HttpGet getimg = new 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(); Scanner in = new Scanner(System.in); responseData = in.nextLine(); in.close(); } 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_uri="+ 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(); String entityxc = EntityUtils.toString(httpentity); System.out.println(entityxc); } /** * * Request Weibo open platform application to return to the login authorization page, but if there is no sessionKey, the login will never be successful. SessionKey is found in the URL placed in an input tag in the returned page, so you need to get this sessionKey. In fact, you can directly access the URL in the tag and jump */ public static String getUrl() throws ClientProtocolException, IOException { HttpGet getcode = new HttpGet("https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id="+ oAuth.getClientId()+ "&response_type=code&redirect_uri=" + oAuth.getRedirectUri()+ "&checkStatus=yes&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 = ""; 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 * @throws Exception */ public static void setToken(HttpGet get) throws Exception { HttpResponse response4 = client.execute(get); HttpEntity entityqqq1 = response4.getEntity(); String getUrlcode = EntityUtils.toString(entityqqq1); // Returns the final jumped page URL, that is, the callback page redirect_uri, and the page address contains code openid openkey // You need to take out these three values separately and splice them into the form of code=xxxxx&openid=xxxxx&openkey=xxxxxxx String 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("code") >= 0 || arr[x].indexOf("openid") >= 0 || arr[x].indexOf("openkey") >= 0) { sb.append(arr[x] + "&"); } ; } // Use code to get accessToken OAuthV2Client.parseAuthorization(sb.substring(0, sb.length() - 1), oAuth); oAuth.setGrantType("authorize_code"); OAuthV2Client.accessToken(oAuth); } /*** * Call (Tengxun Open Platform Account Interface) to get a person's information* @throws Exception */ public static void getInfo() throws Exception { //Output the token. If you get the token, it means that the login is successful and you can perform the next operation. 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) throws Exception { init(oAuth); login("123145", "xxxx"); HttpGet get = new HttpGet(getUrl()); setToken(get); getInfo(); }} 4. There will be corresponding log output when sending successfully
Sina (last line of log):
2078 DEBUG [2013-03-14 16:35:29] {"created_at":"Thu Mar 14 16:35:30 +0800 2013","id":3555791132949940,"mid":"3555791132949940","idstr":"3555791132949940","text":"test","source":"...
Teng Xun:
Log flag for successful login:
ptuiCB('0','0','https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=801216331&response_type=code&redirect_uri=http:','1','Login successfully!', 'ㄗs:ヤDani');View the log flag after the personal information is successful:
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":..
The logs are not listed in full, but are for reference only.
Source code download: http://xiazai.VeVB.COM/201607/yuanma/sinaAndTencent(VeVB.COM).rar
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.