Java爬虫携带sign签名
站点:https://www.mytokencap.com/
代码分析先不写了,大家自行解决,贴代码
1、业务请求设计
public static void md5Pro() {String url = "https://api.mytokenapi.com/ticker/currencylistforall";Map<String, String> headers = new HashMap<>();headers.put("authority", "api.mytokenapi.com");headers.put("accept", "application/json, text/plain, */*");headers.put("accept-language", "en-GB,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");headers.put("cache-control", "no-cache");headers.put("content-type", "application/x-www-form-urlencoded;charset=utf-8");headers.put("origin", "https://www.mytokencap.com");headers.put("pragma", "no-cache");headers.put("referer", "https://www.mytokencap.com/");headers.put("sec-ch-ua", "^\\^Not/A)Brand^^;v=^\\^99^^, ^\\^Google");headers.put("sec-ch-ua-mobile", "?0");headers.put("sec-ch-ua-platform", "^\\^Windows^^");headers.put("sec-fetch-dest", "empty");headers.put("sec-fetch-mode", "cors");headers.put("sec-fetch-site", "cross-site");headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36");long timestamp = System.currentTimeMillis();String code = MD5Example(timestamp + "9527" + String.valueOf(timestamp).substring(0, 6));System.out.println("签名---》" + code);Map<String, String> params = new HashMap<>();params.put("pages", "3,1");params.put("sizes", "100,100");params.put("subject", "market_cap");params.put("language", "en_US");params.put("timestamp", String.valueOf(timestamp));params.put("code", code);params.put("platform", "web_pc");params.put("v", "0.1.0");params.put("legal_currency", "USD");params.put("international", "1");try {String queryString = buildQueryString(params);String fullUrl = url + "?" + queryString;System.out.println("Full URL: " + fullUrl);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}
2、MD5算法设计
public static String MD5Example(String text) {try {MessageDigest md = MessageDigest.getInstance("MD5");byte[] messageDigest = md.digest(text.getBytes());StringBuilder hexString = new StringBuilder();for (byte b : messageDigest) {String hex = Integer.toHexString(0xff & b);if (hex.length() == 1) {hexString.append('0');}hexString.append(hex);}return hexString.toString();} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}}
3、查询参数拼接
public static String buildQueryString(Map<String, String> params) throws UnsupportedEncodingException {SortedMap<String, String> sortedParams = new TreeMap<>(params);StringBuilder query = new StringBuilder();for (Map.Entry<String, String> entry : sortedParams.entrySet()) {if (query.length() > 0) {query.append("&");}query.append(URLEncoder.encode(entry.getKey(), "UTF-8"));query.append("=");query.append(URLEncoder.encode(entry.getValue(), "UTF-8"));}return query.toString();}