查询token接口:/rpc/6051b588 MD5手机号接口(每次消耗1token):/rpc/e0d505b9 MD5姓名接口(每次消耗2token):/rpc/d9998d33 MD5身份证号码接口(每次消耗10token):/rpc/6051b588**
package com.demo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class JavaDemoUtils {
//请求URL
private static final String API_URL = "";
private static final String TOKEN_URL ="";
//密钥
private static final String KEY = "";
public static void main(String[] args) {
queryMd5();
//查询token可用数量
//queryToken();
}
private static void queryMd5(){
Long t = System.currentTimeMillis();
Map<String,Object> param = new HashMap<>();
param.put("key",KEY);
List<String> md5Array = new ArrayList<>();
//模拟md5手机号
for(int i=1;i<=100;i++){
long p = 13000000100L + i;
md5Array.add(md5(String.valueOf(p)));
}
param.put("data",md5Array);
param.put("t",t);
param.put("sign",md5(KEY+t));
Long startTime = System.currentTimeMillis();
httpPost(API_URL,param);
Long endTime = System.currentTimeMillis();
System.out.println("耗时毫秒:"+(endTime-startTime));
}
private static void queryToken(){
Long t = System.currentTimeMillis();
Map<String,Object> param = new HashMap<>();
param.put("key",KEY);
param.put("t",t);
param.put("sign",md5(KEY+t));
httpPost(TOKEN_URL,param);
}
public static void httpPost(String url, Map<String,Object> param){
String reqParam = buildJson(param);
System.out.println("请求参数:"+reqParam);
try{
URL urlObj = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream oStream = httpConn.getOutputStream();
oStream.write(reqParam.getBytes());
oStream.flush();
if (httpConn.getResponseCode() != 200) {
System.out.println("服务断开");
}
BufferedReader br = new BufferedReader( new InputStreamReader(httpConn.getInputStream()));
String resultData = br.readLine();
httpConn.disconnect();
System.out.println("返回结果:"+resultData);
}catch (Exception e){
e.printStackTrace();
System.out.println("服务断开");
}
}
private static String md5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] digestBytes = md.digest();
StringBuilder hexString = new StringBuilder();
for (byte b : digestBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static boolean isNumber(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
private static String buildJson(Map<String, Object> param) {
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{");
String jsonContent = param.entrySet().stream()
.map(entry -> {
String key = "\\"" + entry.getKey() + "\\"";
Object value = entry.getValue();
if (value instanceof List) {
List<?> list = (List<?>) value;
String arrayValue = list.stream()
.map(item -> isNumber(item.toString()) ? item.toString() : "\\"" + item + "\\"")
.collect(Collectors.joining(",", "[", "]"));
return key + ":" + arrayValue;
} else if (isNumber(value.toString())) {
return key + ":" + value;
} else {
return key + ":\\"" + value + "\\"";
}
})
.collect(Collectors.joining(","));
jsonBuilder.append(jsonContent);
jsonBuilder.append("}");
return jsonBuilder.toString();
}
}
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"time"
)
type GoDemoUtils struct {
APIURL string
TOKENURL string
KEY string
}
var (
apiURL = ""
tokenURL = ""
key = ""
)
func main() {
demo := &GoDemoUtils{
APIURL: apiURL,
TOKENURL: tokenURL,
KEY: key,
}
demo.QueryMd5()
// 查询token可用数量
// demo.QueryToken()
}
func (j *GoDemoUtils) QueryMd5() {
t := time.Now().UnixMilli()
param := make(map[string]interface{})
param["key"] = j.KEY
md5Array := make([]string, 0)
// 模拟md5手机号
for i := 1; i <= 100; i++ {
p := 13000000100 + i
md5Array = append(md5Array, j.Md5(strconv.Itoa(p)))
}
param["data"] = md5Array
param["t"] = t
param["sign"] = j.Md5(j.KEY + strconv.FormatInt(t, 10))
startTime := time.Now().UnixMilli()
j.HttpPost(j.APIURL, param)
endTime := time.Now().UnixMilli()
fmt.Printf("耗时毫秒: %d\\n", endTime-startTime)
}
func (j *GoDemoUtils) QueryToken() {
t := time.Now().UnixMilli()
param := make(map[string]interface{})
param["key"] = j.KEY
param["t"] = t
param["sign"] = j.Md5(j.KEY + strconv.FormatInt(t, 10))
j.HttpPost(j.TOKENURL, param)
}
func (j *GoDemoUtils) HttpPost(url string, param map[string]interface{}) {
reqParam, err := j.BuildJson(param)
if err != nil {
fmt.Printf("构建JSON参数失败: %v\\n", err)
return
}
fmt.Printf("请求参数:%s\\n", reqParam)
req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(reqParam)))
if err != nil {
fmt.Printf("创建请求失败: %v\\n", err)
return
}
req.Header.Set("Charset", "UTF-8")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("请求失败: %v\\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Println("服务断开")
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("读取响应失败: %v\\n", err)
return
}
fmt.Printf("返回结果:%s\\n", string(body))
}
func (j *GoDemoUtils) Md5(str string) string {
hash := md5.Sum([]byte(str))
return hex.EncodeToString(hash[:])
}
func (j *GoDemoUtils) IsNumber(str string) bool {
if str == "" {
return false
}
matched, _ := regexp.MatchString(`^[0-9]*$`, str)
return matched
}
func (j *GoDemoUtils) BuildJson(param map[string]interface{}) (string, error) {
jsonData, err := json.Marshal(param)
if err != nil {
return "", err
}
return string(jsonData), nil
}
// 如果需要更精确地控制JSON格式(像Java版本那样),可以使用以下替代方法:
func (j *GoDemoUtils) BuildJsonManual(param map[string]interface{}) string {
var jsonBuilder bytes.Buffer
jsonBuilder.WriteString("{")
first := true
for key, value := range param {
if !first {
jsonBuilder.WriteString(",")
}
first = false
jsonBuilder.WriteString(`"` + key + `":`)
switch v := value.(type) {
case []string:
jsonBuilder.WriteString("[")
for i, item := range v {
if i > 0 {
jsonBuilder.WriteString(",")
}
if j.IsNumber(item) {
jsonBuilder.WriteString(item)
} else {
jsonBuilder.WriteString(`"` + item + `"`)
}
}
jsonBuilder.WriteString("]")
case int, int64, float64:
jsonBuilder.WriteString(fmt.Sprintf("%v", v))
default:
jsonBuilder.WriteString(`"` + fmt.Sprintf("%v", v) + `"`)
}
}
jsonBuilder.WriteString("}")
return jsonBuilder.String()
}
<?php
class PhpDemoUtils {
private $API_URL = "";
private $TOKEN_URL = "";
private $KEY = "";
public function main() {
$this->queryMd5();
// 查询token可用数量
// $this->queryToken();
}
private function queryMd5() {
$t = $this->getMilliseconds();
$param = array();
$param['key'] = $this->KEY;
$md5Array = array();
// 模拟md5手机号
for ($i = 1; $i <= 100; $i++) {
$p = 13000000100 + $i;
$md5Array[] = $this->md5(strval($p));
}
$param['data'] = $md5Array;
$param['t'] = $t;
$param['sign'] = $this->md5($this->KEY . $t);
$startTime = $this->getMilliseconds();
$this->httpPost($this->API_URL, $param);
$endTime = $this->getMilliseconds();
echo "耗时毫秒: " . ($endTime - $startTime) . "\\n";
}
private function queryToken() {
$t = $this->getMilliseconds();
$param = array();
$param['key'] = $this->KEY;
$param['t'] = $t;
$param['sign'] = $this->md5($this->KEY . $t);
$this->httpPost($this->TOKEN_URL, $param);
}
private function httpPost($url, $param) {
$reqParam = $this->buildJson($param);
echo "请求参数:" . $reqParam . "\\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqParam);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Charset: UTF-8'
));
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
echo "服务断开\\n";
curl_close($ch);
return;
}
if (curl_error($ch)) {
echo "请求失败: " . curl_error($ch) . "\\n";
curl_close($ch);
return;
}
curl_close($ch);
echo "返回结果:" . $result . "\\n";
}
private function md5($str) {
return md5($str);
}
private function isNumber($str) {
if ($str === null || trim($str) === '') {
return false;
}
return preg_match('/^[0-9]*$/', $str);
}
private function buildJson($param) {
$jsonParts = array();
foreach ($param as $key => $value) {
$jsonKey = '"' . $key . '"';
if (is_array($value)) {
$arrayValues = array();
foreach ($value as $item) {
if ($this->isNumber(strval($item))) {
$arrayValues[] = $item;
} else {
$arrayValues[] = '"' . $item . '"';
}
}
$jsonValue = '[' . implode(',', $arrayValues) . ']';
$jsonParts[] = $jsonKey . ':' . $jsonValue;
} else if ($this->isNumber(strval($value))) {
$jsonParts[] = $jsonKey . ':' . $value;
} else {
$jsonParts[] = $jsonKey . ':"' . $value . '"';
}
}
return '{' . implode(',', $jsonParts) . '}';
}
private function getMilliseconds() {
return round(microtime(true) * 1000);
}
}
// 使用示例
$demo = new PhpDemoUtils();
$demo->main();
?>
import hashlib
import json
import time
import requests
import re
from typing import Dict, List, Any, Union
class PythonDemoUtils:
def __init__(self):
self.API_URL = ""
self.TOKEN_URL = ""
self.KEY = ""
def main(self):
self.query_md5()
# 查询token可用数量
# self.query_token()
def query_md5(self):
t = self.get_milliseconds()
param = {}
param['key'] = self.KEY
md5_array = []
# 模拟md5手机号
for i in range(1, 101):
p = 13000000100 + i
md5_array.append(self.md5(str(p)))
param['data'] = md5_array
param['t'] = t
param['sign'] = self.md5(self.KEY + str(t))
start_time = self.get_milliseconds()
self.http_post(self.API_URL, param)
end_time = self.get_milliseconds()
print(f"耗时毫秒: {end_time - start_time}")
def query_token(self):
t = self.get_milliseconds()
param = {}
param['key'] = self.KEY
param['t'] = t
param['sign'] = self.md5(self.KEY + str(t))
self.http_post(self.TOKEN_URL, param)
def http_post(self, url: str, param: Dict[str, Any]):
req_param = self.build_json(param)
print(f"请求参数:{req_param}")
try:
headers = {
'Charset': 'UTF-8',
'Content-Type': 'application/json'
}
response = requests.post(
url,
data=req_param,
headers=headers,
timeout=30
)
if response.status_code != 200:
print("服务断开")
return
print(f"返回结果:{response.text}")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
print("服务断开")
def md5(self, text: str) -> str:
return hashlib.md5(text.encode('utf-8')).hexdigest()
def is_number(self, text: str) -> bool:
if text is None or text.strip() == '':
return False
return bool(re.match(r'^[0-9]*$', text))
def build_json(self, param: Dict[str, Any]) -> str:
json_parts = []
for key, value in param.items():
json_key = f'"{key}"'
if isinstance(value, list):
array_values = []
for item in value:
if self.is_number(str(item)):
array_values.append(str(item))
else:
array_values.append(f'"{item}"')
json_value = '[' + ','.join(array_values) + ']'
json_parts.append(f'{json_key}:{json_value}')
elif self.is_number(str(value)):
json_parts.append(f'{json_key}:{value}')
else:
json_parts.append(f'{json_key}:"{value}"')
return '{' + ','.join(json_parts) + '}'
def get_milliseconds(self) -> int:
return int(time.time() * 1000)
# 使用示例
if __name__ == "__main__":
demo = PythonDemoUtils()
demo.main()