• 新浪Java模拟登陆源码


      1 package cn.edu.gdut.weibo.login;
      2 
      3 import java.io.IOException;
      4 import java.net.URLDecoder;
      5 import java.util.ArrayList;
      6 import java.util.Date;
      7 import java.util.List;
      8 
      9 import org.apache.commons.codec.binary.Base64;
     10 import org.apache.commons.logging.Log;
     11 import org.apache.commons.logging.LogFactory;
     12 import org.apache.http.HttpException;
     13 import org.apache.http.HttpResponse;
     14 import org.apache.http.NameValuePair;
     15 import org.apache.http.ParseException;
     16 import org.apache.http.client.ClientProtocolException;
     17 import org.apache.http.client.HttpClient;
     18 import org.apache.http.client.entity.UrlEncodedFormEntity;
     19 import org.apache.http.client.methods.HttpGet;
     20 import org.apache.http.client.methods.HttpPost;
     21 import org.apache.http.message.BasicNameValuePair;
     22 import org.apache.http.protocol.HTTP;
     23 import org.apache.http.util.EntityUtils;
     24 import org.json.JSONException;
     25 import org.json.JSONObject;
     26 
     27 import cn.edu.gdut.util.BigIntegerRSA;
     28 import cn.edu.gdut.util.FileUtil;
     29 import cn.edu.gdut.util.HttpConnectionManager;
     30 import cn.edu.gdut.weibo.model.PreLoginInfo;
     31 
     32 /**
     33  * 
     34  * @author Joe
     35  * 
     36  */
     37 public class WeiboLogin {
     38 
     39     public static String SINA_PK = "EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D24"
     40             + "5A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD39"
     41             + "93CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE"
     42             + "1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443";
     43     public static String username = FileUtil.getUname();//FileUtil就是获取配置文件
     44     public static String passwd = FileUtil.getPwd();
     45 
     46     private static final Log logger = LogFactory.getLog(WeiboLogin.class);
     47 
     48     public static HttpClient getLoginStatus() {
     49 
     50         final HttpClient client = HttpConnectionManager.getHttpClient();
     51         HttpPost post = new HttpPost(
     52                 "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.2)");
     53 
     54         PreLoginInfo info = null;
     55         try {
     56             info = getPreLoginBean(client);
     57         } catch (HttpException e) {
     58             e.printStackTrace();
     59             logger.error(e);
     60         } catch (IOException e) {
     61             e.printStackTrace();
     62             logger.error("登陆失败,请确认已连接正确网络!" + e);
     63             return null;
     64         } catch (JSONException e) {
     65             e.printStackTrace();
     66             logger.error(e);
     67         }
     68 
     69         long servertime = info.servertime;
     70         String nonce = info.nonce;
     71 
     72         String pwdString = servertime + "\t" + nonce + "\n" + passwd;
     73         String sp = new BigIntegerRSA().rsaCrypt(SINA_PK, "10001", pwdString);
     74 
     75         List<NameValuePair> nvps = new ArrayList<NameValuePair>();
     76         nvps.add(new BasicNameValuePair("entry", "weibo"));
     77         nvps.add(new BasicNameValuePair("gateway", "1"));
     78         nvps.add(new BasicNameValuePair("from", ""));
     79         nvps.add(new BasicNameValuePair("savestate", "7"));
     80         nvps.add(new BasicNameValuePair("useticket", "1"));
     81         nvps.add(new BasicNameValuePair("ssosimplelogin", "1"));
     82         nvps.add(new BasicNameValuePair("vsnf", "1"));
     83         // new NameValuePair("vsnval", ""),
     84         nvps.add(new BasicNameValuePair("su", encodeUserName(username)));
     85         nvps.add(new BasicNameValuePair("service", "miniblog"));
     86         nvps.add(new BasicNameValuePair("servertime", servertime + ""));
     87         nvps.add(new BasicNameValuePair("nonce", nonce));
     88         nvps.add(new BasicNameValuePair("pwencode", "rsa2"));
     89         nvps.add(new BasicNameValuePair("rsakv", info.rsakv));
     90         nvps.add(new BasicNameValuePair("sp", sp));
     91         nvps.add(new BasicNameValuePair("encoding", "UTF-8"));
     92         nvps.add(new BasicNameValuePair("prelt", "115"));
     93         nvps.add(new BasicNameValuePair("returntype", "META"));
     94         nvps.add(new BasicNameValuePair(
     95                 "url",
     96                 "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));
     97 
     98         try {
     99             post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    100             HttpResponse response = client.execute(post);
    101             String entity = EntityUtils.toString(response.getEntity());
    102             if (entity.indexOf("code=0") == -1) {
    103                 logger.error("登陆失败:"
    104                         + URLDecoder.decode(entity.substring(
    105                                 entity.indexOf("reason=") + 7,
    106                                 entity.indexOf("&#39;\"/>"))));
    107                 System.out.println("登陆失败:"
    108                         + URLDecoder.decode(entity.substring(
    109                                 entity.indexOf("reason=") + 7,
    110                                 entity.indexOf("&#39;\"/>"))));
    111                 return null;
    112             }
    113 
    114             String url = entity.substring(
    115                     entity.indexOf("http://weibo.com/ajaxlogin.php?"),
    116                     entity.indexOf("code=0") + 6);
    117 
    118             HttpGet getMethod = new HttpGet(url);
    119             response = client.execute(getMethod);
    120             entity = EntityUtils.toString(response.getEntity());
    121             logger.info("用户名:"
    122                     + username
    123                     + "登陆成功!\n"
    124                     + entity.substring(entity.indexOf("({"),
    125                             entity.indexOf(";</script>")));
    139         } catch (ParseException e) {
    140             e.printStackTrace();
    141             logger.error(e);
    142         } catch (ClientProtocolException e) {
    143             e.printStackTrace();
    144             logger.error(e);
    145         } catch (IOException e) {
    146             e.printStackTrace();
    147             logger.error(e);
    148         }
    149         return client;
    150     }
    151 
    152     private static PreLoginInfo getPreLoginBean(HttpClient client)
    153             throws HttpException, IOException, JSONException {
    154 
    155         String serverTime = getPreLoginInfo(client);
    156         JSONObject jsonInfo = new JSONObject(serverTime);
    157         PreLoginInfo info = new PreLoginInfo();
    158         info.nonce = jsonInfo.getString("nonce");
    159         info.pcid = jsonInfo.getString("pcid");
    160         info.pubkey = jsonInfo.getString("pubkey");
    161         info.retcode = jsonInfo.getInt("retcode");
    162         info.rsakv = jsonInfo.getString("rsakv");
    163         info.servertime = jsonInfo.getLong("servertime");
    164         return info;
    165     }
    166 
    167     public static String getPreLoginInfo(HttpClient client)
    168             throws ParseException, IOException {
    169         String preloginurl = "http://login.sina.com.cn/sso/prelogin.php?entry=sso&"
    170                 + "callback=sinaSSOController.preloginCallBack&su="
    171                 + "dW5kZWZpbmVk"
    172                 + "&rsakt=mod&client=ssologin.js(v1.4.2)"
    173                 + "&_=" + getCurrentTime();
    174         HttpGet get = new HttpGet(preloginurl);
    175 
    176         HttpResponse response = client.execute(get);
    177 
    178         String getResp = EntityUtils.toString(response.getEntity());
    179 
    180         int firstLeftBracket = getResp.indexOf("(");
    181         int lastRightBracket = getResp.lastIndexOf(")");
    182 
    183         String jsonBody = getResp.substring(firstLeftBracket + 1,
    184                 lastRightBracket);
    185         // System.out.println(jsonBody);
    186         return jsonBody;
    187 
    188     }
    189 
    190     private static String getCurrentTime() {
    191         long servertime = new Date().getTime() / 1000;
    192         return String.valueOf(servertime);
    193     }
    194 
    195     private static String encodeUserName(String email) {
    196         email = email.replaceFirst("@", "%40");// MzM3MjQwNTUyJTQwcXEuY29t
    197         email = Base64.encodeBase64String(email.getBytes());
    198         return email;
    199     }
    200 
    201 }
     1 package cn.edu.gdut.util;
     2 
     3 
     4 import java.io.UnsupportedEncodingException;
     5 import java.math.BigInteger;
     6 import java.security.InvalidKeyException;
     7 import java.security.KeyFactory;
     8 import java.security.NoSuchAlgorithmException;
     9 import java.security.interfaces.RSAPublicKey;
    10 import java.security.spec.InvalidKeySpecException;
    11 import java.security.spec.RSAPublicKeySpec;
    12 
    13 import javax.crypto.BadPaddingException;
    14 import javax.crypto.Cipher;
    15 import javax.crypto.IllegalBlockSizeException;
    16 import javax.crypto.NoSuchPaddingException;
    17 
    18 import org.apache.commons.codec.binary.Hex;
    19 import org.apache.commons.logging.Log;
    20 import org.apache.commons.logging.LogFactory;
    21 
    22 public class BigIntegerRSA {
    23     private static final Log logger = LogFactory.getLog(BigIntegerRSA.class);
    24     public static String SINA_PUB = "EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D24"
    25             + "5A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD39"
    26             + "93CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE"
    27             + "1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443";
    28     
    29     public String rsaCrypt(String modeHex, String exponentHex, String messageg){
    30         
    31         BigInteger m = new BigInteger(modeHex, 16); /* public exponent */
    32         BigInteger e = new BigInteger(exponentHex, 16); /* modulus */
    33         RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    34         
    35         RSAPublicKey pub;
    36         byte[] encryptedContentKey = null;
    37         try {
    38             KeyFactory factory = KeyFactory.getInstance("RSA");
    39             pub = (RSAPublicKey) factory.generatePublic(spec);
    40             Cipher enc = Cipher.getInstance("RSA");
    41             enc.init(Cipher.ENCRYPT_MODE, pub);
    42             encryptedContentKey = enc.doFinal(messageg.getBytes("GB2312"));
    43         } catch (InvalidKeySpecException e1) {
    44             logger.error( e1);
    45         } catch (NoSuchAlgorithmException e1) {
    46             logger.error( e1);
    47         } catch (NoSuchPaddingException e1) {
    48             logger.error( e1);
    49         } catch (InvalidKeyException e1) {
    50             logger.error( e1);
    51         } catch (IllegalBlockSizeException e1) {
    52             logger.error( e1);
    53         } catch (BadPaddingException e1) {
    54             logger.error( e1);
    55         } catch (UnsupportedEncodingException e1) {
    56             logger.error( e1);
    57         }
    58          
    59         return new String(Hex.encodeHex(encryptedContentKey));
    60     }
    61 }
     1 package cn.edu.gdut.util;
     2 
     3 import org.apache.http.HttpHost;
     4 import org.apache.http.client.HttpClient;
     5 import org.apache.http.client.params.ClientPNames;
     6 import org.apache.http.conn.routing.HttpRoute;
     7 import org.apache.http.conn.scheme.PlainSocketFactory;
     8 import org.apache.http.conn.scheme.Scheme;
     9 import org.apache.http.conn.scheme.SchemeRegistry;
    10 import org.apache.http.conn.ssl.SSLSocketFactory;
    11 import org.apache.http.cookie.Cookie;
    12 import org.apache.http.cookie.CookieOrigin;
    13 import org.apache.http.cookie.CookieSpec;
    14 import org.apache.http.cookie.CookieSpecFactory;
    15 import org.apache.http.cookie.MalformedCookieException;
    16 import org.apache.http.impl.client.DefaultHttpClient;
    17 import org.apache.http.impl.conn.PoolingClientConnectionManager;
    18 import org.apache.http.impl.cookie.BrowserCompatSpec;
    19 import org.apache.http.params.BasicHttpParams;
    20 import org.apache.http.params.HttpConnectionParams;
    21 import org.apache.http.params.HttpParams;
    22 
    23 public class HttpConnectionManager {
    24 
    25     public static HttpClient getHttpClient() {
    26         HttpParams params = new BasicHttpParams();
    27         /* 连接超时 */
    28         HttpConnectionParams.setConnectionTimeout(params, 3000);
    29         /* 请求超时 */
    30         HttpConnectionParams.setSoTimeout(params, 10000);
    31         SchemeRegistry schemeRegistry = new SchemeRegistry();
    32         schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
    33                 .getSocketFactory()));
    34         schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
    35                 .getSocketFactory()));
    36 
    37         PoolingClientConnectionManager cm = new PoolingClientConnectionManager(
    38                 schemeRegistry);
    39         // Increase max total connection to 200
    40         cm.setMaxTotal(200);
    41         // Increase default max connection per route to 20
    42         cm.setDefaultMaxPerRoute(20);
    43         // Increase max connections for localhost:80 to 50
    44         HttpHost localhost = new HttpHost("locahost", 80);
    45         cm.setMaxPerRoute(new HttpRoute(localhost), 50);
    46 
    47         DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
    48         // 自定义cookies*****************
    49         CookieSpecFactory csf = new CookieSpecFactory() {
    50             public CookieSpec newInstance(HttpParams params) {
    51                 return new BrowserCompatSpec() {
    52                     @Override
    53                     public void validate(Cookie cookie, CookieOrigin origin)
    54                             throws MalformedCookieException {
    55                         // Oh, I am easy
    56                     }
    57                 };
    58             }
    59         };
    60 
    61         httpClient.getCookieSpecs().register("easy", csf);
    62         httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, "easy");
    63         // 自定义cookies*****************
    64         return httpClient;
    65     }
    66 
    67 }
     1 public class PreLoginInfo {
     2     public long servertime;
     3     public String nonce;
     4     public String pubkey;
     5     public String pcid;
     6     public int retcode;
     7     public String rsakv;
     8     
     9     
    10 }

    上面三个就是新浪模拟登陆的代码,应该不难。。。BigIntegerRSA是用来对密码进行2次sha加密的。HttpConnectionManager其实就是用来设置HttpClient参数的。还有问题留言吧。

  • 相关阅读:
    Python学习之旅—生成器对象的send方法详解
    对集合多列进行求和方法的选择
    23种设计模式
    这一天,我真正的体会到。。。
    火狐浏览器导出EXCEL 表格,文件名乱码问题
    K-fold Train Version3
    K-fold Train Version2
    K-fold Train
    Confusion matrix
    Kaggle Solutions
  • 原文地址:https://www.cnblogs.com/joeman/p/3039279.html
Copyright © 2020-2023  润新知