suiyuan 发表于 2022-10-1 21:02:55

谷歌翻译API破解 Java源代码

package com.coding.easier.util;

import kong.unirest.Header;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
* @author :zhuYi
* @date :Created in 2022/10/1 3:04
*/

public class YoudaoFanyiUtil {
    private static String COOKIE;
    private static long COOKIE_VALIDITY_TIME;

    private static String getCookie() {
      if (COOKIE == null) {
            COOKIE = createCookie();
            if (COOKIE != null) {
                //3小时更新一次
                COOKIE_VALIDITY_TIME = System.currentTimeMillis() + (3 * 60 * 60 * 1000);
                return COOKIE;
            }
      } else if (System.currentTimeMillis() > COOKIE_VALIDITY_TIME) {
            //过期了刷新COOKIE
            COOKIE = null;
            return getCookie();
      } else {
            return COOKIE;
      }
      return null;
    }

    private static String createCookie() {
      HttpResponse<String> response = Unirest.get("https://fanyi.youdao.com/")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/xxx.x.xxxx.xx")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .asString();
      for (Header header : response.getHeaders().all()) {
            if ("Set-Cookie".equals(header.getName())) {
                String cookie = header.getValue();
                String txt = cookie.substring(cookie.indexOf("OUTFOX_SEARCH_USER_ID="));
                txt = txt.substring(0, txt.indexOf(";"));
                return String.format("%s; ___rl__test__cookies=", txt);
            }
      }
      return null;
    }

    /**
   * 欲翻译的内容
   */
    public static void translation(final String txt, Callback callback) {
      new Thread(() -> {
            try {
                //Cookie检查
                if (getCookie() == null) {
                  return;
                }
                //统一编码,否则插件中无法使用
                String coding = getEncoding(txt);
                String str = coding.equals("UTF-8") ? txt : new String(txt.getBytes(), "GBK");
                String url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule";
                String u = "fanyideskweb";
                String ctime = System.currentTimeMillis() + "";
                //int random = (int) (Math.random() * 10 + 1); idea内置API有问题
                int random = new Random().nextInt(9);
                String f = ctime + "" + random;
                String c = "Ygy_4c=r#e#4EX^NUGUc5";
                //浏览器版本信息
                String bv = md5("5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/xxx.x.xxxx.xx");
                //插件内置编码不兼容 ,故改用byte进行md5处理
                byte[] strBytes = str.getBytes("UTF8");
                byte[] uBytes = u.getBytes();
                byte[] fBytes = f.getBytes();
                byte[] cBytes = c.getBytes();
                byte[] newMd5Bytes = new byte;
                System.arraycopy(uBytes, 0, newMd5Bytes, 0, uBytes.length);
                System.arraycopy(strBytes, 0, newMd5Bytes, uBytes.length, strBytes.length);
                System.arraycopy(fBytes, 0, newMd5Bytes, strBytes.length + uBytes.length, fBytes.length);
                System.arraycopy(cBytes, 0, newMd5Bytes, fBytes.length + uBytes.length + strBytes.length, cBytes.length);
                String sign = md5(newMd5Bytes);
                Map<String, String> params = new HashMap<>();
                params.put("i", URLEncoder.encode(str, "UTF-8"));
                params.put("from", "AUTO");
                params.put("to", "AUTO");
                params.put("smartresult", "dict");
                params.put("client", u);
                params.put("salt", f);
                params.put("lts", ctime);
                params.put("bv", bv);
                params.put("sign", sign);
                params.put("doctype", "json");
                params.put("version", "2.1");
                params.put("keyfrom", "fanyi.web");
                params.put("action", "FY_BY_REALTlME");
                StringBuilder stringBuilder = new StringBuilder();
                for (String key : params.keySet()) {
                  stringBuilder.append("&" + key + "=" + params.get(key));
                }
                HttpResponse<String> response = Unirest.post(url)
                        .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                        .header("Cookie", getCookie() + ctime)
                        .header("Referer", "http://fanyi.youdao.com/")
                        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/xxx.x.xxxx.xx")
                        .body(stringBuilder.toString())
                        .asString();
                int status = response.getStatus();
                if (status >= 200 && status < 300) {
                  callback.OnResponse(response.getBody());
                } else if (status == 429) {
                  System.err.println("请求次数过多,可能触发了限流,请稍候再试......");
                } else {
                  System.err.println("Unexpected response status: " + status);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }

      }).start();
    }


    /**
   * 生成32位MD5摘要
   *
   * @param string
   * @return
   */
    private static String md5(String string) {
      if (string == null) {
            return null;
      }
      char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
      byte[] btInput = string.getBytes();
      try {
            /** 获得MD5摘要算法的 MessageDigest 对象 */
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            /** 使用指定的字节更新摘要 */
            mdInst.update(btInput);
            /** 获得密文 */
            byte[] md = mdInst.digest();
            /** 把密文转换成十六进制的字符串形式 */
            int j = md.length;
            char str[] = new char;
            int k = 0;
            for (byte byte0 : md) {
                str = hexDigits;
                str = hexDigits;
            }
            return new String(str).toLowerCase();
      } catch (NoSuchAlgorithmException e) {
            return null;
      }
    }

    private static String md5(byte[] btInput) {
      char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
      try {
            /** 获得MD5摘要算法的 MessageDigest 对象 */
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            /** 使用指定的字节更新摘要 */
            mdInst.update(btInput);
            /** 获得密文 */
            byte[] md = mdInst.digest();
            /** 把密文转换成十六进制的字符串形式 */
            int j = md.length;
            char str[] = new char;
            int k = 0;
            for (byte byte0 : md) {
                str = hexDigits;
                str = hexDigits;
            }
            return new String(str).toLowerCase();
      } catch (NoSuchAlgorithmException e) {
            return null;
      }
    }


    public static String getEncoding(String str) {
      String encode = "GB2312";
      try {
            if (isEncoding(str, encode)) { // 判断是不是GB2312
                return encode;
            }
      } catch (Exception exception) {
      }
      encode = "ISO-8859-1";
      try {
            if (isEncoding(str, encode)) { // 判断是不是ISO-8859-1
                return encode;
            }
      } catch (Exception exception1) {
      }
      encode = "UTF-8";
      try {
            if (isEncoding(str, encode)) { // 判断是不是UTF-8
                return encode;
            }
      } catch (Exception exception2) {
      }
      encode = "GBK";
      try {
            if (isEncoding(str, encode)) { // 判断是不是GBK
                return encode;
            }
      } catch (Exception exception3) {
      }
      return ""; // 如果都不是,说明输入的内容不属于常见的编码格式。
    }

    public static boolean isEncoding(String str, String encode) {
      try {
            if (str.equals(new String(str.getBytes(), encode))) {
                return true;
            }
      } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
      }
      return false;
    }

    public interface Callback {
      void OnResponse(String str);

    }

}


suiyuan 发表于 2022-10-1 21:04:02

应该叫有道,标题整错了,随意吧,送给有缘人

慕宇 发表于 2022-10-4 22:06:22

学习一下,谢谢楼主分享

逗逼 发表于 2022-11-1 11:17:09

学习了

clown1360 发表于 2023-8-21 18:46:15

看一下。,
页: [1]
查看完整版本: 谷歌翻译API破解 Java源代码