Java simulation Sina and Tencent automatically login and send microblogging _java

Source: Internet
Author: User
Tags md5 oauth openid stringbuffer

Java simulation Sina and Tencent automatic login and send microblogging functions to share to everyone for your reference, the specific content as follows

1. Preparatory work
just log in no need to apply for Sina and Tencent developer account, if you need to send microblogging function, need to apply for a Sina and Tencent developer account, and add a test application.

Process please refer to the official Help document, application address: Sina:http://open.weibo.com Tencent:http://dev.t.qq.com/

What we need is app key and app Secre and Redirect_uri, the source code already contains the test key that I applied for, but because of the limitation of using my key directly your account is unable to login successfully.

2. Matters needing attention
1), the application of the app key and app Secre and Redirect_uri, corresponding to the project root directory in the config.properties configuration file
client_id=1745656892
Client_sercret=66056719c1d8ca7bcaf36f411217cefa
Redirect_uri=www.baidu.com
Redirect_uri because it is only testing and there is no direct callback page, so just fill in an address on the line, but pay attention to the application-advanced settings in the "callback page" consistent.
2, the code in the test account needs to add their own test account, Sina's "Application Information-Test account"; Tencent in "permission control-Create whitelist". Of course, directly with the developer account can also.
3), sent Weibo cited Sina's Weibo4j-oauth2-beta2.1.1.zip, Tencent'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; /*** * Analog Automatic login concurrency micro bo * @author ZDW * */public class Sina {/*** * impersonate login and get login token * @param username username * @param PA ssWOrd Password * @return * @throws httpexception * @throws ioexception * * public static Accesstoken GetToken (String Userna
  me,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);
  Application of the app Key Postmethod.addparameter ("client_id", clientId);
  Applied redirect page Postmethod.addparameter ("Redirect_uri", Redirecturi);
  Simulate 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 

2), Tencent

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; /*** * Automatic login and get personal information * @author ZDW */public class Tencent {public static final String hexstring = 0123456789ABCD
 EF ";
 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 * Authentication code * @return Encrypted password * @throws unsupportedencodingexception * @throws Exception * * */public static string GetPassword (String qq, string password, string verifycode) throws exc
 eption {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 = n
 EW 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 to New String (Baos.tobytearray (), "iso-8859-1"); /*** * Analog Login * @param QQ QQ number * @param password QQ password * @throws Exception * * public static void login (String QQ, S Tring 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 CAPTCHA output to c:/code.jpg, after viewing enter to continue to execute if ("1". Equals (Checknum[0)) {//UIn for QQ number or Weibo username httpget getimg = new HTTPG ET ("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%2f%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 microblogging open platform application to return to login authorization page, but if there is no sessionkey words forever login unsuccessful SessionKey * found in returnPage in an input tag in the URL, so to get to this sessionkey actually direct access to the URL in the tag can be jump * * */public static String GetUrl () throws Clientprotocolexce Ption, 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&
 Amp;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=\ ")); /** * resolves and sets 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 page URL of the final jump, that is, the callback page Redirect_uri, the page address contains the code OpenID Openkey//need to remove these three values individually and then spliced into code=xxxxx&openid=xxxxx&
 openkey=xxxxxx form 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] + "&");
 }
  ;
 ///Using code to obtain Accesstoken oauthv2client.parseauthorization (sb.substring (0, Sb.length ()-1), OAuth);
 Oauth.setgranttype ("Authorize_code");
 Oauthv2client.accesstoken (OAuth); /*** * Call (Tencent Open Platform account interface) Get a person's information * @throws Exception/public static void GetInfo () thrOWS Exception {//output token, if you get the token on behalf of the success of the login, and can take the next steps.
 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. The sending success has the corresponding log output
Sina (last line of log):

2078 DEBUG [2013-03-14 16:35:29] {"Created_at": "Thu Mar 16:35:30 +0800 2013", "ID": 3555791132949940, "Mid": " 3555791132949940 "," Idstr ":" 3555791132949940 "," text ":" Test "," source ":" ...

Tencent

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 successful! ', ' ㄗs:ヤ '); View the log flag for successful personal information:

Qhttpclient HttpGet [3] Response = {"Data": {"birth_day": num, "Birth_month": 8, "birth_year": *, "City_code": "2", "comp" : null, "Country_code": "1", "edu": null, "email": "", "exp": "Fansnum":

The log is not fully listed, just as a reference.

SOURCE Download: Http://xiazai.jb51.net/201607/yuanma/sinaAndTencent (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.