微博開放平台採用 OAuth 2.0 授權碼模式。本文示範「後台模擬登錄 → 獲取 Authorization Code → 換取 Access Token → 調用發布介面」的完整自動化流程,適用於測試、爬蟲或無前端環境的服務端發布。
微博登錄密碼非明文傳輸,而是由 JavaScript (sinaSSOEncoder) 在客戶端完成 RSA 加密。Java 端需:
prelogin 介面獲取 servertime、nonce、pubkey、rsakv。javax.script) 跑官方加密邏輯,產生 sp (加密後密碼)。su (Base64 編碼用戶名)、sp 等參數 POST 登錄。String su = Base64.getEncoder().encodeToString(URLEncoder.encode(username, "UTF-8").getBytes());
String preloginUrl = "https://login.sina.com.cn/sso/prelogin.php?entry=account&su=" + su + "&rsakt=mod&client=ssologin.js(v1.4.19)&_=" + System.currentTimeMillis();
// 解析 JSON 回應,取得 servertime, nonce, pubkey, rsakv
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); // Java 8+ 內建
engine.eval(JS_ENCRYPT_CODE); // 官方 sinaSSOEncoder 完整 JS 代碼
Invocable inv = (Invocable) engine;
String sp = (String) inv.invokeFunction("getpass", password, servertime, nonce, pubkey);
// 登錄 POST
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("entry", "account"),
new BasicNameValuePair("gateway", "1"),
new BasicNameValuePair("su", su),
new BasicNameValuePair("servertime", String.valueOf(servertime)),
new BasicNameValuePair("nonce", nonce),
new BasicNameValuePair("pwencode", "rsa2"),
new BasicNameValuePair("rsakv", rsakv),
new BasicNameValuePair("sp", sp),
// ... 其他必要欄位
);
// 執行請求,保存所有 Set-Cookie
// 依序訪問 crossDomainUrlList 完成單點登入同步
// 使用 HttpClientContext 捕獲重導向鏈
HttpClientContext context = HttpClientContext.create();
HttpGet get = new HttpGet(authorizeUrl);
get.setHeader("Cookie", savedCookies);
CloseableHttpResponse resp = httpClient.execute(get, context);
List<URI> redirects = context.getRedirectLocations();
// 從最後一個重導向 URL 中提取 code=xxx
// 使用 weibo4j-sdk
Oauth oauth = new Oauth();
AccessToken token = oauth.getAccessTokenByCode(code);
Timeline tm = new Timeline(token.getAccessToken());
Status status = tm.updateStatus("Hello from Java Auto Post!");
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>weibo4j</groupId>
<artifactId>weibo4j</artifactId>
<version>2.0.0</version> // 需自行安裝或用最新 fork 版
</dependency>
nashorn-core 或改用 GraalVM JS。BasicCookieStore 全程保持會話,跨域同步步驟不可省略。Location Header 並提取 code。雖然微博官方建議前端導向授權,但在自動化測試、內部工具、無瀏覽器環境下,後台模擬完整登錄授權流程是可行的。關鍵在於精確還原前端 RSA2 加密邏輯與正確處理 OAuth 重導向鏈。