【3003接口】Token和Base64字符串生成工具

上传图片并生成符合要求的token和base64编码字符串

输入信息

点击或拖拽图片到此处上传

支持 JPG, PNG, BMP 格式,最短边至少15px,最长边最大4096px

预览图:

图片预览

生成结果

字符串长度: 0 字节

调用示例代码

以下是使用不同编程语言调用API接口的示例代码

所有参数(action、base64_urlencode_imagestring、user、token)均通过POST表单提交

Python
Java
C#
JavaScript
PHP
Go
import requests
import base64
import hashlib

# 配置信息
username = "your_username"
password = "your_password"
action = "vin_ocr_and_vin_decode"
image_path = r"d:/temp/vintest.png"
api_url = "http://api.17vin.com:8080/"

# 读取图片并进行Base64编码
with open(image_path, "rb") as image_file:
    # 对图片进行Base64编码
    base64_image = base64.b64encode(image_file.read()).decode('utf-8')
    # 对Base64字符串进行URL编码
    url_encoded_image = requests.utils.quote(base64_image)

# 构建POST表单参数
post_data = {
    "action": action,
    "base64_urlencode_imagestring": url_encoded_image,
    "user": username
}

# 生成Token所需的参数字符串
# 注意:生成Token时需要使用未编码的action和已编码的base64字符串
token_params = f"action={action}&base64_urlencode_imagestring={url_encoded_image}"

# 生成Token
def md5_hash(text):
    return hashlib.md5(text.encode('utf-8')).hexdigest()

md5_user = md5_hash(username)
md5_password = md5_hash(password)
token = md5_hash(md5_user + md5_password + token_params)

# 添加Token到POST数据
post_data["token"] = token

# 发送POST请求,参数放在表单中
try:
    response = requests.post(api_url, data=post_data)
    # 输出响应结果
    print("响应状态码:", response.status_code)
    print("响应内容:", response.text)
except Exception as e:
    print("请求出错:", str(e))
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class ApiClient {
    public static void main(String[] args) {
        try {
            // 配置信息
            String username = "your_username";
            String password = "your_password";
            String action = "vin_ocr_and_vin_decode";
            String imagePath = "d:/temp/vintest.png";
            String apiUrl = "http://api.17vin.com:8080/";
            
            // 读取图片并进行Base64编码
            byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            String urlEncodedImage = URLEncoder.encode(base64Image, "UTF-8");
            
            // 构建POST表单参数
            Map<String, String> postData = new HashMap<>();
            postData.put("action", action);
            postData.put("base64_urlencode_imagestring", urlEncodedImage);
            postData.put("user", username);
            
            // 生成Token所需的参数字符串
            String tokenParams = "action=" + action + 
                               "&base64_urlencode_imagestring=" + urlEncodedImage;
            
            // 生成Token
            String md5User = md5(username);
            String md5Password = md5(password);
            String token = md5(md5User + md5Password + tokenParams);
            
            // 添加Token到POST数据
            postData.put("token", token);
            
            // 构建POST请求
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            
            // 写入POST参数
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.writeBytes(getPostDataString(postData));
                wr.flush();
            }
            
            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("响应状态码: " + responseCode);
            
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            
            // 输出响应结果
            System.out.println("响应内容: " + response.toString());
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 将Map转换为POST参数字符串
    private static String getPostDataString(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first) {
                first = false;
            } else {
                result.append("&");
            }
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }
    
    // MD5加密方法
    private static String md5(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.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();
    }
}
/*
常见问题:Content-Type 被默认设置为 text/plain; charset=ISO-8859-1,但是对于表单数据(URL 编码)通常应该使用 application/x-www-form-urlencoded 作为 Content-Type这个问题
 //java提交案例
 private String submitForm(String baseUrl, String action, String base64StringUrlEncode, String user, String token) throws IOException {
    // 创建HttpClient实例
    CloseableHttpClient client = HttpClients.createDefault();

    // 创建HttpPost请求
    HttpPost httpPost = new HttpPost(baseUrl);

    // 构建请求参数
    Map form = new HashMap<>();
    form.put("action", action);
    form.put("base64_urlencode_imagestring", base64StringUrlEncode);
    form.put("user", user);
    form.put("token", token);

    // 构建URL编码的表单数据
    List nameValuePairs = new ArrayList<>();
    for (Map.Entry entry : form.entrySet()) {
    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    // 设置请求体为表单数据,Content-Type 为 application/x-www-form-urlencoded
    HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
    httpPost.setEntity(entity);

    // 执行请求
    try (CloseableHttpResponse response = client.execute(httpPost)) {
    // 处理响应
    return EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (Exception e) {
    return e.getMessage();
    } finally {
    client.close(); // 确保HttpClient也被关闭
    }
}
     */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Gather_vin_api_
{
    public class test_api_3003
    {
        public static void TestApi_post_3003()
        {
            string local_imgpath = @"d:/temp/vintest.png";
            string user = "user_xxx";//这里更改您的用户名  user_xxx 
            string pass = "password_xxx";//这里更改您的密码 password_xxx 

            string action = "vin_ocr_and_vin_decode";
            byte[] imageBytes = File.ReadAllBytes(local_imgpath);
            string base64String = Convert.ToBase64String(imageBytes);
            string base64String_urlencode = System.Net.WebUtility.UrlEncode(base64String);
            string url_parameters = "/?action=" + action + "&base64_urlencode_imagestring=" + base64String_urlencode;
            string token = getToken(user, pass, url_parameters);

            string baseUrl = "http://api.17vin.com:8080";
            // 调用函数提交表单
            string response = SubmitForm(baseUrl, action, base64String_urlencode, user, token);
            // 输出响应内容  
            Console.WriteLine(response);
        }
        public static string SubmitForm(string baseUrl, string action, string base64String_urlencode, string user, string token)
        {
            // 创建 HttpClient 实例
            using (HttpClient client = new HttpClient())
            {
                // 创建 HttpRequestMessage 对象
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, baseUrl);

                // 构建请求体内容
                string requestBody = $"action={action}&user={user}&token={token}&base64_urlencode_imagestring={EncodeInParts(base64String_urlencode)}";
                request.Content = new StringContent(requestBody, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");

                // 发送请求,并获取响应内容
                HttpResponseMessage response = client.SendAsync(request).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;

                return responseBody;


            }
        }
        /// 
        /// 分段解码,解决大图错误,如无效的 URI: URI 字符串太长
        /// 
        /// 
        /// 
        private static string EncodeInParts(string input)
        {
            const int partLength = 250; // 可根据需要调整分段长度
            StringBuilder encodedBuilder = new StringBuilder();
            for (int i = 0; i < input.Length; i += partLength)
            {
                string part = input.Substring(i, Math.Min(partLength, input.Length - i));
                encodedBuilder.Append(Uri.EscapeDataString(part));
            }
            return encodedBuilder.ToString();
        }
        public static string SubmitForm_shortimg(string baseUrl, string action, string base64String_urlencode, string user, string token)
        {
            // 创建HttpClient实例  
            using (HttpClient client = new HttpClient())
            {
                // 设置请求的URL  
                client.BaseAddress = new Uri(baseUrl);

                // 创建表单数据的键值对集合  
                var formContent = new FormUrlEncodedContent(new[]
                {
                new KeyValuePair("action", action),
                new KeyValuePair("base64_urlencode_imagestring", base64String_urlencode),
                new KeyValuePair("user", user),
                new KeyValuePair("token", token)
            });

                // 发送POST请求,并获取响应内容  
                HttpResponseMessage response = client.PostAsync("", formContent).Result; // 同步等待响应  
                response.EnsureSuccessStatusCode(); // 抛出异常,如果请求不成功  
                string responseBody = response.Content.ReadAsStringAsync().Result; // 同步读取响应内容  

                return responseBody;
            }
        }
        private static string getMd5(string ConvertString)
        {
            MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider();
            return BitConverter.ToString(mD5CryptoServiceProvider.ComputeHash(Encoding.UTF8.GetBytes(ConvertString))).Replace("-", "").ToLower();
        }
        private static string getToken(string user, string pass, string url_parameters)
        {
            return getMd5(getMd5(user) + getMd5(pass) + url_parameters);
        }
    }
} 
// Node.js环境示例
const fs = require('fs');
const https = require('https');
const http = require('http');
const crypto = require('crypto');
const querystring = require('querystring');

// 配置信息
const username = "your_username";
const password = "your_password";
const action = "vin_ocr_and_vin_decode";
const imagePath = "d:/temp/vintest.png";
const apiUrl = "http://api.17vin.com:8080/";

// MD5加密函数
function md5Hash(text) {
    return crypto.createHash('md5').update(text).digest('hex');
}

// 读取图片并处理
fs.readFile(imagePath, (err, imageData) => {
    if (err) {
        console.error("读取图片出错:", err);
        return;
    }
    
    try {
        // 图片Base64编码
        const base64Image = imageData.toString('base64');
        // URL编码
        const urlEncodedImage = encodeURIComponent(base64Image);
        
        // 构建POST表单参数
        const postData = {
            action: action,
            base64_urlencode_imagestring: urlEncodedImage,
            user: username
        };
        
        // 生成Token所需的参数字符串
        const tokenParams = `action=${action}&base64_urlencode_imagestring=${urlEncodedImage}`;
        
        // 生成Token
        const md5User = md5Hash(username);
        const md5Password = md5Hash(password);
        const token = md5Hash(md5User + md5Password + tokenParams);
        
        // 添加Token到POST数据
        postData.token = token;
        
        // 转换为表单格式
        const postDataString = querystring.stringify(postData);
        
        // 解析URL
        const parsedUrl = new URL(apiUrl);
        const options = {
            hostname: parsedUrl.hostname,
            port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
            path: parsedUrl.pathname,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(postDataString)
            }
        };
        
        // 发送POST请求
        const client = parsedUrl.protocol === 'https:' ? https : http;
        const request = client.request(options, (response) => {
            console.log(`响应状态码: ${response.statusCode}`);
            
            response.on('data', (data) => {
                console.log('响应内容:', data.toString());
            });
        });
        
        // 写入POST数据
        request.write(postDataString);
        
        request.on('error', (error) => {
            console.error('请求出错:', error);
        });
        
        request.end();
    } catch (error) {
        console.error('处理出错:', error);
    }
});
<?php
// 配置信息
$username = "your_username";
$password = "your_password";
$action = "vin_ocr_and_vin_decode";
$imagePath = "d:/temp/vintest.png";
$apiUrl = "http://api.17vin.com:8080/";

try {
    // 读取图片并进行Base64编码
    $imageData = file_get_contents($imagePath);
    if ($imageData === false) {
        throw new Exception("无法读取图片文件");
    }
    
    $base64Image = base64_encode($imageData);
    $urlEncodedImage = urlencode($base64Image);
    
    // 构建POST表单参数
    $postData = array(
        'action' => $action,
        'base64_urlencode_imagestring' => $urlEncodedImage,
        'user' => $username
    );
    
    // 生成Token所需的参数字符串
    $tokenParams = "action={$action}&base64_urlencode_imagestring={$urlEncodedImage}";
    
    // 生成Token
    $md5User = md5($username);
    $md5Password = md5($password);
    $token = md5($md5User . $md5Password . $tokenParams);
    
    // 添加Token到POST数据
    $postData['token'] = $token;
    
    // 初始化cURL
    $ch = curl_init();
    
    // 设置cURL选项
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); // POST参数放在表单中
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // 执行请求并获取响应
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // 检查错误
    if(curl_errno($ch)) {
        throw new Exception("cURL错误: " . curl_error($ch));
    }
    
    // 关闭cURL
    curl_close($ch);
    
    // 输出结果
    echo "响应状态码: {$httpCode}\n";
    echo "响应内容: {$response}\n";
    
} catch (Exception $e) {
    echo "请求出错: " . $e->getMessage() . "\n";
}
?>
package main

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
)

func main() {
	// 配置信息
	username := "your_username"
	password := "your_password"
	action := "vin_ocr_and_vin_decode"
	imagePath := "d:/temp/vintest.png"
	apiUrl := "http://api.17vin.com:8080/"

	// 读取图片文件
	imageData, err := ioutil.ReadFile(imagePath)
	if err != nil {
		fmt.Printf("读取图片出错: %v\n", err)
		return
	}

	// 图片Base64编码
	base64Image := base64.StdEncoding.EncodeToString(imageData)
	
	// URL编码
	urlEncodedImage := url.QueryEscape(base64Image)

	// 构建POST表单参数
	formData := url.Values{}
	formData.Set("action", action)
	formData.Set("base64_urlencode_imagestring", urlEncodedImage)
	formData.Set("user", username)
	
	// 生成Token所需的参数字符串
	tokenParams := fmt.Sprintf("action=%s&base64_urlencode_imagestring=%s", 
		action, urlEncodedImage)

	// 生成MD5哈希
	md5User := fmt.Sprintf("%x", md5.Sum([]byte(username)))
	md5Password := fmt.Sprintf("%x", md5.Sum([]byte(password)))
	token := fmt.Sprintf("%x", md5.Sum([]byte(md5User+md5Password+tokenParams)))

	// 添加Token到POST数据
	formData.Set("token", token)

	// 发送POST请求,参数放在表单中
	resp, err := http.PostForm(apiUrl, formData)
	if err != nil {
		fmt.Printf("请求出错: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("读取响应出错: %v\n", err)
		return
	}

	// 输出结果
	fmt.Printf("响应状态码: %d\n", resp.StatusCode)
	fmt.Printf("响应内容: %s\n", string(body))
}