Crawler4JavbusServiceImpl.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. package top.lvzhiqiang.service.impl;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.github.pagehelper.PageHelper;
  4. import com.github.pagehelper.PageInfo;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.jsoup.Connection;
  7. import org.jsoup.HttpStatusException;
  8. import org.jsoup.Jsoup;
  9. import org.jsoup.nodes.Document;
  10. import org.jsoup.nodes.Element;
  11. import org.jsoup.select.Elements;
  12. import org.springframework.beans.factory.annotation.Value;
  13. import org.springframework.scheduling.annotation.Async;
  14. import org.springframework.stereotype.Service;
  15. import org.springframework.util.StopWatch;
  16. import top.lvzhiqiang.entity.CrawlerJavbusLog;
  17. import top.lvzhiqiang.entity.CrawlerJavbusProfile;
  18. import top.lvzhiqiang.entity.DicCode;
  19. import top.lvzhiqiang.mapper.CrawlerJavbusProfileMapper;
  20. import top.lvzhiqiang.mapper.DicCodeMapper;
  21. import top.lvzhiqiang.service.Crawler4JavbusService;
  22. import top.lvzhiqiang.util.DateUtils;
  23. import top.lvzhiqiang.util.JsoupUtil;
  24. import top.lvzhiqiang.util.StringUtils;
  25. import javax.annotation.Resource;
  26. import java.io.BufferedReader;
  27. import java.io.InputStreamReader;
  28. import java.net.HttpURLConnection;
  29. import java.net.InetSocketAddress;
  30. import java.net.Proxy;
  31. import java.net.URL;
  32. import java.time.LocalDateTime;
  33. import java.util.*;
  34. import java.util.stream.Collectors;
  35. /**
  36. * Crawler Javbus ServiceImpl
  37. *
  38. * @author lvzhiqiang
  39. * 2022/10/17 14:47
  40. */
  41. @Service
  42. @Slf4j
  43. public class Crawler4JavbusServiceImpl implements Crawler4JavbusService {
  44. @Resource
  45. private DicCodeMapper dicCodeMapper;
  46. @Resource
  47. private CrawlerJavbusProfileMapper crawlerJavbusProfileMapper;
  48. @Value("${spring.profiles.active}")
  49. private String env;
  50. Map<String, String> javbusConstantMap = null;
  51. Map<String, String> javbusCookiesMap = null;
  52. String bdAccessToken = "";
  53. Proxy proxy = null;
  54. public void beforeJavbus() throws Exception {
  55. if (null == proxy) {
  56. if ("dev".equals(env)) {
  57. proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1080));
  58. } else {
  59. proxy = Proxy.NO_PROXY;
  60. }
  61. }
  62. if (StringUtils.isEmpty(bdAccessToken)) {
  63. bdAccessToken = getAuth(javbusConstantMap.get("bd_ak"), javbusConstantMap.get("bd_sk"));
  64. }
  65. if (null == javbusCookiesMap) {
  66. for (int i = 0; i < 3; i++) {
  67. if (generateJavbusCookies(proxy)) {
  68. break;
  69. } else {
  70. javbusCookiesMap = null;
  71. }
  72. }
  73. if (javbusCookiesMap == null) {
  74. throw new Exception("获取javbusCookies失败!");
  75. }
  76. }
  77. }
  78. @Async
  79. @Override
  80. public void jsoupJavbusProfile(Long start, Integer limit) throws Exception {
  81. log.warn("jsoupJavbusProfile 开始:start={},limit={}", start, limit);
  82. StopWatch stopWatch = new StopWatch();
  83. stopWatch.start();
  84. // 获取javbus常量MAP
  85. javbusConstantMap = dicCodeMapper.findAll().stream()
  86. .filter(x -> "javbus".equals(x.getCodeDesc()) && x.getEnv().contains(env))
  87. .collect(Collectors.toMap(DicCode::getCodeKey, DicCode::getCodeValue, (key1, key2) -> key1));
  88. // 代理及TOKEN设置
  89. beforeJavbus();
  90. // 获取个人资料
  91. jsoupJavbusProfileSub(start, limit);
  92. log.warn("jsoupJavbusProfile 结束:time={}", stopWatch.getTotalTimeSeconds());
  93. }
  94. @Async
  95. @Override
  96. public void handleJavbusLog(Integer status) throws Exception {
  97. log.warn("handleJavbusLog 开始:status={}", status);
  98. StopWatch stopWatch = new StopWatch();
  99. stopWatch.start();
  100. // 获取javbus常量MAP
  101. javbusConstantMap = dicCodeMapper.findAll().stream()
  102. .filter(x -> "javbus".equals(x.getCodeDesc()) && x.getEnv().contains(env))
  103. .collect(Collectors.toMap(DicCode::getCodeKey, DicCode::getCodeValue, (key1, key2) -> key1));
  104. // 代理及TOKEN设置
  105. beforeJavbus();
  106. // 获取个人资料
  107. handleJavbusLogSub(status);
  108. log.warn("handleJavbusLog 结束:time={}", stopWatch.getTotalTimeSeconds());
  109. }
  110. @Override
  111. public String findJavbusProfile(String keyword, Integer timeDay, Integer pic, String orderField, String order, Integer pageNo, Integer pageSize) {
  112. Map<String, Object> params = new HashMap<>();
  113. params.put("keyword", keyword);
  114. params.put("timeDay", timeDay);
  115. params.put("orderField", orderField);
  116. params.put("order", order);
  117. PageHelper.startPage(pageNo, pageSize);
  118. List<CrawlerJavbusProfile> crawlerJavbusProfileList = crawlerJavbusProfileMapper.findJavbusProfile4MultipleParams(params);
  119. PageInfo<CrawlerJavbusProfile> javbusProfilePageInfo = new PageInfo<>(crawlerJavbusProfileList);
  120. StringBuffer sb = new StringBuffer("total:".concat(String.valueOf(javbusProfilePageInfo.getTotal())).concat("<br/>"));
  121. sb.append("<table border=\"1\" cellspacing=\"0\"><tr><th>UID</th><th>昵称</th><th>邮箱状态</th><th>好友数</th><th>回帖数</th><th>主题数</th><th>用户组</th><th>在线时间</th><th>注册时间</th><th>上次活动时间</th><th>上次发表时间</th><th>所在时区</th><th>头像</th><th>个人签名文字</th><th>个人签名图片</th></tr>");
  122. for (CrawlerJavbusProfile crawlerJavbusProfile : crawlerJavbusProfileList) {
  123. sb.append("<tr>");
  124. sb.append("<td>").append(crawlerJavbusProfile.getUid()).append("</td>");
  125. sb.append("<td>").append(crawlerJavbusProfile.getEmailStatus()).append("</td>");
  126. sb.append("<td>").append(crawlerJavbusProfile.getFriendNum()).append("</td>");
  127. sb.append("<td>").append(crawlerJavbusProfile.getReplyNum()).append("</td>");
  128. sb.append("<td>").append(crawlerJavbusProfile.getThreadNum()).append("</td>");
  129. sb.append("<td>").append(crawlerJavbusProfile.getUserGroup()).append("</td>");
  130. sb.append("<td>").append(crawlerJavbusProfile.getOnlineTime()).append("</td>");
  131. sb.append("<td>").append(crawlerJavbusProfile.getRegistrationTime()).append("</td>");
  132. sb.append("<td>").append(crawlerJavbusProfile.getLastActivityTime()).append("</td>");
  133. sb.append("<td>").append(crawlerJavbusProfile.getLastPublishedTime()).append("</td>");
  134. sb.append("<td>").append(crawlerJavbusProfile.getTimeZone()).append("</td>");
  135. if (pic == 2) {
  136. sb.append("<td>").append("<img src=\"" + crawlerJavbusProfile.getAvatarUrl() + "\" alt=\"封面\" width=\"147\" height=\"auto\">").append("</td>");
  137. } else {
  138. sb.append("<td>").append(crawlerJavbusProfile.getAvatarUrl()).append("</td>");
  139. }
  140. sb.append("<td>").append(crawlerJavbusProfile.getSignStr()).append("</td>");
  141. if (pic == 2) {
  142. sb.append("<td>");
  143. String signImg = crawlerJavbusProfile.getSignImg();
  144. if (StringUtils.isNotEmpty(signImg)) {
  145. for (String s : signImg.split(",")) {
  146. sb.append("<img src=\"" + s + "\" alt=\"sign\" width=\"147\" height=\"auto\">");
  147. }
  148. } else {
  149. sb.append("--");
  150. }
  151. sb.append("</td>");
  152. } else {
  153. if (StringUtils.isNotEmpty(crawlerJavbusProfile.getSignImg())) {
  154. sb.append("<td>").append(crawlerJavbusProfile.getSignImg()).append("</td>");
  155. } else {
  156. sb.append("<td>--</td>");
  157. }
  158. }
  159. sb.append("</tr>");
  160. }
  161. sb.append("</table>");
  162. return sb.toString();
  163. }
  164. private void handleJavbusLogSub(Integer status) {
  165. List<CrawlerJavbusLog> javbusLogByStatus = crawlerJavbusProfileMapper.findJavbusLogByStatus(status);
  166. String profileUrl = "https://www.javbus.com/forum/?";
  167. Document profileDocument;
  168. for (CrawlerJavbusLog javbusLog : javbusLogByStatus) {
  169. try {
  170. profileDocument = JsoupUtil.requestDocument(profileUrl.concat(javbusLog.getBusinessKey()), JsoupUtil.HTTP_GET, proxy, javbusCookiesMap, null, null);
  171. if (profileDocument.html().contains("您指定的用戶空間不存在")) {
  172. log.warn("jsoupJavbusProfileSub您指定的用戶空間不存在,start={}", javbusLog.getBusinessKey());
  173. continue;
  174. }
  175. CrawlerJavbusProfile crawlerJavbusProfile = new CrawlerJavbusProfile();
  176. parseJavbusProfile(profileDocument, crawlerJavbusProfile);
  177. crawlerJavbusProfileMapper.insertOrUpdate(crawlerJavbusProfile);
  178. log.warn("jsoupJavbusProfileSub成功插入,businessKey={}", javbusLog.getBusinessKey());
  179. javbusLog.setStatus(2);
  180. javbusLog.setErrorMsg("");
  181. } catch (Exception e) {
  182. log.error("jsoupJavbusProfileSub插入异常,businessKey={}", javbusLog.getBusinessKey(), e);
  183. javbusLog.setStatus(3);
  184. javbusLog.setErrorMsg(e.getMessage());
  185. }
  186. crawlerJavbusProfileMapper.insertOrUpdateLog(javbusLog);
  187. }
  188. }
  189. private void jsoupJavbusProfileSub(Long start, Integer limit) {
  190. CrawlerJavbusProfile latestJavbusProfile = crawlerJavbusProfileMapper.findLatestInfo();
  191. if (start == null && latestJavbusProfile == null) {
  192. start = 1L;
  193. } else if (start == null && latestJavbusProfile != null) {
  194. start = latestJavbusProfile.getUid() + 1;
  195. }
  196. long startFinal = 0;
  197. if (limit != null) {
  198. startFinal = start + limit;
  199. }
  200. String profileUrl = "https://www.javbus.com/forum/?";
  201. Document profileDocument;
  202. int continueCount = 0;
  203. while (true) {
  204. if (startFinal != 0 && start > startFinal) {
  205. log.warn("jsoupJavbusProfileSub结束,start={},startFinal={}", start, startFinal);
  206. return;
  207. }
  208. if (start > 500000 && continueCount > 10) {
  209. log.warn("jsoupJavbusProfileSub结束,start={},continueCount={}", start, continueCount);
  210. return;
  211. }
  212. try {
  213. profileDocument = JsoupUtil.requestDocument(profileUrl.concat(String.valueOf(start)), JsoupUtil.HTTP_GET, proxy, javbusCookiesMap, null, null);
  214. if (profileDocument.html().contains("您指定的用戶空間不存在")) {
  215. log.warn("jsoupJavbusProfileSub您指定的用戶空間不存在,start={}", start);
  216. start++;
  217. continueCount++;
  218. continue;
  219. }
  220. CrawlerJavbusProfile crawlerJavbusProfile = new CrawlerJavbusProfile();
  221. parseJavbusProfile(profileDocument, crawlerJavbusProfile);
  222. crawlerJavbusProfileMapper.insertOrUpdate(crawlerJavbusProfile);
  223. log.warn("jsoupJavbusProfileSub成功插入,start={}", start);
  224. } catch (Exception e) {
  225. log.error("jsoupJavbusProfileSub插入异常,start={}", start, e);
  226. CrawlerJavbusLog crawlerJavbusLog = new CrawlerJavbusLog();
  227. crawlerJavbusLog.setType(1);
  228. crawlerJavbusLog.setStatus(1);
  229. crawlerJavbusLog.setBusinessKey(String.valueOf(start));
  230. crawlerJavbusLog.setErrorMsg(e.getMessage());
  231. crawlerJavbusProfileMapper.insertOrUpdateLog(crawlerJavbusLog);
  232. }
  233. start++;
  234. }
  235. }
  236. public void parseJavbusProfile(Document profileDocument, CrawlerJavbusProfile crawlerJavbusProfile) {
  237. String avatarUrl = profileDocument.select("div.avt").select("img").attr("src");
  238. String[] mbn0Arr = profileDocument.select("div.u_profile").select("div.cl").get(0).select("h2.mbn").get(0).text().replace("(", "").replace(")", "").split("UID:");
  239. String nickName = mbn0Arr[0].trim();
  240. String uid = mbn0Arr[1].trim();
  241. String emailStatus = profileDocument.select("div.u_profile").select("div.cl").get(0).select("ul").first().text().replace("郵箱狀態", "").trim();
  242. Elements signEles = profileDocument.select("div.u_profile").select("div.cl").get(0).select("ul").get(1).select("li:contains(個人簽名)");
  243. String signStr = "";
  244. ArrayList<String> signImgList = new ArrayList<>();
  245. if (signEles.size() > 0) {
  246. signStr = signEles.first().select("table").text();
  247. Elements signImgEles = signEles.first().select("table").select("img");
  248. for (Element signImgEle : signImgEles) {
  249. signImgList.add(signImgEle.attr("src"));
  250. }
  251. }
  252. String friendNum = profileDocument.select("div.u_profile").select("div.cl").get(0).select("ul").get(2)
  253. .select("a").get(0).text().replace("好友數", "").trim();
  254. String replyNum = profileDocument.select("div.u_profile").select("div.cl").get(0).select("ul").get(2)
  255. .select("a").get(1).text().replace("回帖數", "").trim();
  256. String threadNum = profileDocument.select("div.u_profile").select("div.cl").get(0).select("ul").get(2)
  257. .select("a").get(2).text().replace("主題數", "").trim();
  258. String userGroup = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(0)
  259. .select("a").text();
  260. String onlineTime = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(1)
  261. .select("li:contains(在線時間)").text().replace("在線時間", "").replace("小時", "").trim();
  262. String registrationTime = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(1)
  263. .select("li:contains(註冊時間)").text().replace("註冊時間", "").trim();
  264. String lastVisit = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(1)
  265. .select("li:contains(最後訪問)").text().replace("最後訪問", "").trim();
  266. String lastActivityTime = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(1)
  267. .select("li:contains(上次活動時間)").text().replace("上次活動時間", "").trim();
  268. String lastPublishedTime = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(1)
  269. .select("li:contains(上次發表時間)").text().replace("上次發表時間", "").trim();
  270. String timeZone = profileDocument.select("div.u_profile").select("div.cl").get(1).select("ul").get(1)
  271. .select("li:contains(所在時區)").text().replace("所在時區", "").trim();
  272. String usedSpace = profileDocument.select("div.u_profile").select("div.cl").get(2).select("ul").get(0)
  273. .select("li").get(0).text().replace("已用空間", "").replace("B", "").trim();
  274. String mileage = profileDocument.select("div.u_profile").select("div.cl").get(2).select("ul").get(0)
  275. .select("li").get(1).text().replace("里程", "").trim();
  276. String money = profileDocument.select("div.u_profile").select("div.cl").get(2).select("ul").get(0)
  277. .select("li").last().text().replace("金錢", "").trim();
  278. crawlerJavbusProfile.setUid(Long.valueOf(uid));
  279. crawlerJavbusProfile.setNickName(nickName);
  280. crawlerJavbusProfile.setEmailStatus(emailStatus);
  281. crawlerJavbusProfile.setFriendNum(Integer.valueOf(friendNum));
  282. crawlerJavbusProfile.setReplyNum(Integer.valueOf(replyNum));
  283. crawlerJavbusProfile.setThreadNum(Integer.valueOf(threadNum));
  284. crawlerJavbusProfile.setUserGroup(userGroup);
  285. crawlerJavbusProfile.setOnlineTime(StringUtils.isNotEmpty(onlineTime) ? Integer.valueOf(onlineTime) : null);
  286. crawlerJavbusProfile.setRegistrationTime(StringUtils.isNotEmpty(registrationTime) && registrationTime.length() >= 10 ? LocalDateTime.parse(registrationTime, DateUtils.dateTimeFormatter3) : null);
  287. crawlerJavbusProfile.setLastVisit(StringUtils.isNotEmpty(lastVisit) && lastVisit.length() >= 10 ? LocalDateTime.parse(lastVisit, DateUtils.dateTimeFormatter3) : null);
  288. crawlerJavbusProfile.setLastActivityTime(StringUtils.isNotEmpty(lastActivityTime) && lastActivityTime.length() >= 10 ? LocalDateTime.parse(lastActivityTime, DateUtils.dateTimeFormatter3) : null);
  289. crawlerJavbusProfile.setLastPublishedTime(StringUtils.isNotEmpty(lastPublishedTime) && lastPublishedTime.length() >= 10 ? LocalDateTime.parse(lastPublishedTime, DateUtils.dateTimeFormatter3) : null);
  290. crawlerJavbusProfile.setTimeZone(StringUtils.isNotEmpty(timeZone) ? timeZone : null);
  291. crawlerJavbusProfile.setUsedSpace(Integer.valueOf(usedSpace));
  292. crawlerJavbusProfile.setMileage(Integer.valueOf(mileage));
  293. crawlerJavbusProfile.setMoney(Integer.valueOf(money));
  294. crawlerJavbusProfile.setAvatarUrl(avatarUrl);
  295. crawlerJavbusProfile.setSignStr(signStr);
  296. crawlerJavbusProfile.setSignImg(org.apache.commons.lang3.StringUtils.join(signImgList, ","));
  297. }
  298. private boolean generateJavbusCookies(Proxy proxy) throws Exception {
  299. // 1 登陆获取cookies
  300. // 1.0 https://www.javbus.com/forum/forum.php
  301. Connection.Response forumResponse = JsoupUtil.requestBody(javbusConstantMap.get("forum_url"), JsoupUtil.HTTP_GET, proxy, null);
  302. Map<String, String> forumCookies = forumResponse.cookies();
  303. log.warn("generateJavbusCookies=>,forum_url={},forumCookies={}", javbusConstantMap.get("forum_url"), forumCookies);
  304. // 1.1 https://www.javbus.com/forum/member.php
  305. Map<String, String> params = new HashMap<>(8);
  306. params.put("mod", "logging");
  307. params.put("action", "login");
  308. params.put("referer", "");
  309. params.put("infloat", "yes");
  310. params.put("handlekey", "login");
  311. params.put("inajax", "1");
  312. params.put("ajaxtarget", "fwin_content_login");
  313. String memberHtmlStr = JsoupUtil.requestDocument(javbusConstantMap.get("member_url"), JsoupUtil.HTTP_GET, proxy, forumCookies, null, params).html().replace("<![CDATA[", "").replace("]]>", "");
  314. Document memberDocument = Jsoup.parse(memberHtmlStr);
  315. String key1 = memberDocument.select("input[type='password']").first().attr("id").split("_")[1];
  316. String key2 = memberDocument.select("span[id^='seccode']").first().attr("id").split("_")[1];
  317. String key3 = memberDocument.select("input[name='formhash']").first().val();
  318. // 1.2 https://www.javbus.com/forum/misc.php
  319. params.clear();
  320. params.put("mod", "seccode");
  321. params.put("action", "update");
  322. params.put("idhash", key2);
  323. params.put("modid", "member::logging");
  324. Document miscDocument = JsoupUtil.requestDocument(javbusConstantMap.get("misc_url"), JsoupUtil.HTTP_GET, proxy, forumCookies, null, params);
  325. String imgVerifyUrl = "https://www.javbus.com/forum/" + miscDocument.select("img[onclick]").first().attr("src");
  326. // 1.3 get verifyImg
  327. Map<String, String> headerParams = new HashMap<>(8);
  328. headerParams.put("referer", javbusConstantMap.get("forum_url"));
  329. Connection.Response imgResponse = JsoupUtil.requestBody(imgVerifyUrl, JsoupUtil.HTTP_GET, proxy, forumCookies, headerParams, null);
  330. byte[] imgBytes = imgResponse.bodyAsBytes();
  331. Map<String, String> imgCookies = imgResponse.cookies();
  332. log.warn("generateJavbusCookies=>,imgVerifyUrl={},imgCookies={}", imgVerifyUrl, imgCookies);
  333. String cookieKey4Seccode = "";
  334. for (Map.Entry<String, String> imgCookie : imgCookies.entrySet()) {
  335. if (imgCookie.getKey().contains("seccode")) {
  336. cookieKey4Seccode = imgCookie.getKey();
  337. break;
  338. }
  339. }
  340. // 1.4 get imgVerifyNumber by BaiduOCR
  341. headerParams.clear();
  342. headerParams.put("Content-Type", "application/x-www-form-urlencoded");
  343. params.clear();
  344. params.put("image", Base64.getEncoder().encodeToString(imgBytes));
  345. JSONObject crAccurateBasicResult = null;
  346. String seccodeverify = "";
  347. for (int i = 0; i < 3; i++) {
  348. try {
  349. Connection.Response ocrResponse = JsoupUtil.requestBody(javbusConstantMap.get("bd_ocr_url").concat("?access_token=").concat(bdAccessToken),
  350. JsoupUtil.HTTP_POST, Proxy.NO_PROXY, headerParams, params);
  351. crAccurateBasicResult = JSONObject.parseObject(ocrResponse.body());
  352. seccodeverify = crAccurateBasicResult.getJSONArray("words_result").getJSONObject(0).getString("words");
  353. break;
  354. } catch (HttpStatusException hse) {
  355. bdAccessToken = getAuth(javbusConstantMap.get("bd_ak"), javbusConstantMap.get("bd_sk"));
  356. } catch (Exception e) {
  357. log.error("BaiduOCR异常,bdOcrUrl={},bdAccessToken={},crAccurateBasicResult={}", javbusConstantMap.get("bd_ocr_url"), bdAccessToken, crAccurateBasicResult, e);
  358. if (i == 2) {
  359. throw new Exception("BaiduOCR异常!");
  360. }
  361. }
  362. }
  363. // 1.5 https://www.javbus.com/forum/member.php
  364. String sbParams = "?mod=logging&action=login&loginsubmit=yes&handlekey=login&loginhash=" + key1 + "&inajax=1";
  365. headerParams.clear();
  366. headerParams.put("Content-Type", "application/x-www-form-urlencoded");
  367. params.clear();
  368. params.put("formhash", key3);
  369. params.put("referer", javbusConstantMap.get("forum_url"));
  370. params.put("loginfield", "username");
  371. params.put("username", javbusConstantMap.get("username"));
  372. params.put("password", javbusConstantMap.get("password"));
  373. params.put("questionid", "0");
  374. params.put("answer", "");
  375. params.put("seccodehash", key2);
  376. params.put("seccodemodid", "member::logging");
  377. params.put("seccodeverify", seccodeverify);
  378. if (cookieKey4Seccode != "") {
  379. forumCookies.put("existmag", "mag");
  380. forumCookies.put(cookieKey4Seccode, imgCookies.get(cookieKey4Seccode));
  381. }
  382. String loginUrl = javbusConstantMap.get("member_url").concat(sbParams);
  383. Connection.Response loginResponse = JsoupUtil.requestBody(loginUrl, JsoupUtil.HTTP_POST, proxy, forumCookies, headerParams, params);
  384. String loginBody = loginResponse.body();
  385. Map<String, String> loginCookies = loginResponse.cookies();
  386. log.warn("generateJavbusCookies=>,loginUrl={},params={},forumCookies={},loginCookies={},loginResponseBody={}", loginUrl, params, forumCookies, loginCookies, loginResponse.body());
  387. for (Map.Entry<String, String> loginCookie : loginCookies.entrySet()) {
  388. if (loginCookie.getKey().contains("ulastactivity")) {
  389. forumCookies.put(loginCookie.getKey(), loginCookie.getValue());
  390. } else if (loginCookie.getKey().contains("auth")) {
  391. forumCookies.put(loginCookie.getKey(), loginCookie.getValue());
  392. } else if (loginCookie.getKey().contains("lastcheckfeed")) {
  393. forumCookies.put(loginCookie.getKey(), loginCookie.getValue());
  394. } else if (loginCookie.getKey().contains("lip")) {
  395. forumCookies.put(loginCookie.getKey(), loginCookie.getValue());
  396. }
  397. }
  398. log.warn("generateJavbusCookies=>,forumFinalCookies={}", forumCookies);
  399. javbusCookiesMap = forumCookies;
  400. return loginBody.contains("歡迎您回來");
  401. }
  402. public String getAuth(String ak, String sk) {
  403. // 获取token地址
  404. String authHost = javbusConstantMap.get("bd_authhost_url");
  405. String getAccessTokenUrl = authHost
  406. // 1. grant_type为固定参数
  407. + "grant_type=client_credentials"
  408. // 2. 官网获取的 API Key
  409. + "&client_id=" + ak
  410. // 3. 官网获取的 Secret Key
  411. + "&client_secret=" + sk;
  412. try {
  413. URL realUrl = new URL(getAccessTokenUrl);
  414. // 打开和URL之间的连接
  415. HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
  416. connection.setRequestMethod("GET");
  417. connection.connect();
  418. // 获取所有响应头字段
  419. Map<String, List<String>> map = connection.getHeaderFields();
  420. // 遍历所有的响应头字段
  421. /*for (String key : map.keySet()) {
  422. System.err.println(key + "--->" + map.get(key));
  423. }*/
  424. // 定义 BufferedReader输入流来读取URL的响应
  425. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  426. String result = "";
  427. String line;
  428. while ((line = in.readLine()) != null) {
  429. result += line;
  430. }
  431. /**
  432. * 返回结果示例
  433. */
  434. System.err.println("result:" + result);
  435. JSONObject jsonObject = JSONObject.parseObject(result);
  436. String access_token = jsonObject.getString("access_token");
  437. return access_token;
  438. } catch (Exception e) {
  439. System.err.print("获取token失败!");
  440. e.printStackTrace(System.err);
  441. }
  442. return null;
  443. }
  444. }