体验向量搜索
示例文档
从文档中通过文本搜索
JavaScript
const axios = require('axios');
const CryptoJS = require('crypto-js');
const formState = {
content: '向量数据库的优势是什么',
num: 1,
includeMeta: false,
};
// 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
const app_key = 'xxx'; // 替换为自己的app_key
const app_secret = 'xxx'; // 替换为自己的app_secret
function getSignParams() {
const timestamp = Date.now().toString();
const nonce_str = Math.random().toString(36).substring(8);
// 对参数按key进行字典排序
const params = { app_key, app_secret, timestamp, nonce_str };
const keys = Object.keys(params).sort();
const str = keys.map((key) => `${key}=${params[key]}`).join('&');
// MD5加密
params.signature = CryptoJS.MD5(str).toString();
return params;
}
async function search() {
try {
const response = await axios({
url: 'https://api.yiruocloud.com/vector/search',
method: 'post',
headers: {
...getSignParams(),
},
data: {
...formState,
includeMeta: formState.includeMeta ? 1 : 0,
},
});
if (response.data.code !== 0) {
console.error(response.data || '搜索失败');
return null;
}
console.log(response.data);
return response.data.data;
} catch (error) {
console.error(error || '未知错误');
throw error;
}
}
search();
const axios = require('axios');
const CryptoJS = require('crypto-js');
const formState = {
content: '向量数据库的优势是什么',
num: 1,
includeMeta: false,
};
// 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
const app_key = 'xxx'; // 替换为自己的app_key
const app_secret = 'xxx'; // 替换为自己的app_secret
function getSignParams() {
const timestamp = Date.now().toString();
const nonce_str = Math.random().toString(36).substring(8);
// 对参数按key进行字典排序
const params = { app_key, app_secret, timestamp, nonce_str };
const keys = Object.keys(params).sort();
const str = keys.map((key) => `${key}=${params[key]}`).join('&');
// MD5加密
params.signature = CryptoJS.MD5(str).toString();
return params;
}
async function search() {
try {
const response = await axios({
url: 'https://api.yiruocloud.com/vector/search',
method: 'post',
headers: {
...getSignParams(),
},
data: {
...formState,
includeMeta: formState.includeMeta ? 1 : 0,
},
});
if (response.data.code !== 0) {
console.error(response.data || '搜索失败');
return null;
}
console.log(response.data);
return response.data.data;
} catch (error) {
console.error(error || '未知错误');
throw error;
}
}
search();
Java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import okhttp3.*;
public class Main {
private static final String app_key = "xxx"; // 替换为自己的app_key
private static final String app_secret = "xxx"; // 替换为自己的app_secret
public static void main(String[] args) {
Map<String, String> formState = new HashMap<>();
formState.put("content", "向量数据库的优势是什么");
formState.put("num", "1");
formState.put("includeMeta", "false");
try {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("content", formState.get("content"))
.add("num", formState.get("num"))
.add("includeMeta", formState.get("includeMeta"))
.build();
Request request = new Request.Builder()
.url("https://api.allaihub.chat/vector/search")
.post(requestBody)
.headers(Headers.of(getSignParams()))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("搜索失败");
return;
}
String responseData = response.body().string();
System.out.println(responseData);
} catch (Exception e) {
System.out.println("未知错误");
e.printStackTrace();
}
}
private static Map<String, String> getSignParams() throws NoSuchAlgorithmException {
String timestamp = String.valueOf(System.currentTimeMillis());
String nonce_str = UUID.randomUUID().toString().substring(0, 8);
Map<String, String> params = new HashMap<>();
params.put("app_key", app_key);
params.put("app_secret", app_secret);
params.put("timestamp", timestamp);
params.put("nonce_str", nonce_str);
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
StringBuilder sb = new StringBuilder();
for (String key : keys) {
sb.append(key).append("=").append(params.get(key)).append("&");
}
sb.deleteCharAt(sb.length() - 1);
String signature = md5(sb.toString());
params.put("signature", signature);
return params;
}
private static String md5(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
}
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import okhttp3.*;
public class Main {
private static final String app_key = "xxx"; // 替换为自己的app_key
private static final String app_secret = "xxx"; // 替换为自己的app_secret
public static void main(String[] args) {
Map<String, String> formState = new HashMap<>();
formState.put("content", "向量数据库的优势是什么");
formState.put("num", "1");
formState.put("includeMeta", "false");
try {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("content", formState.get("content"))
.add("num", formState.get("num"))
.add("includeMeta", formState.get("includeMeta"))
.build();
Request request = new Request.Builder()
.url("https://api.allaihub.chat/vector/search")
.post(requestBody)
.headers(Headers.of(getSignParams()))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("搜索失败");
return;
}
String responseData = response.body().string();
System.out.println(responseData);
} catch (Exception e) {
System.out.println("未知错误");
e.printStackTrace();
}
}
private static Map<String, String> getSignParams() throws NoSuchAlgorithmException {
String timestamp = String.valueOf(System.currentTimeMillis());
String nonce_str = UUID.randomUUID().toString().substring(0, 8);
Map<String, String> params = new HashMap<>();
params.put("app_key", app_key);
params.put("app_secret", app_secret);
params.put("timestamp", timestamp);
params.put("nonce_str", nonce_str);
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
StringBuilder sb = new StringBuilder();
for (String key : keys) {
sb.append(key).append("=").append(params.get(key)).append("&");
}
sb.deleteCharAt(sb.length() - 1);
String signature = md5(sb.toString());
params.put("signature", signature);
return params;
}
private static String md5(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
}
Python
import requests
import hashlib
import time
import random
formState = {
'content': '向量数据库的优势是什么',
'num': 1,
'includeMeta': False,
}
# 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
app_key = 'xxx' # 替换为自己的app_key
app_secret = 'xxx' # 替换为自己的app_secret
def getSignParams():
timestamp = str(int(time.time() * 1000))
nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))
# 对参数按key进行字典排序
params = {'app_key': app_key, 'app_secret': app_secret, 'timestamp': timestamp, 'nonce_str': nonce_str}
keys = sorted(params.keys())
_str = '&'.join([f'{key}={params[key]}' for key in keys])
# MD5加密
params['signature'] = hashlib.md5(_str.encode()).hexdigest()
return params
def search():
try:
response = requests.post(
url='https://api.yiruocloud.com/vector/search',
headers=getSignParams(),
json={
**formState,
'includeMeta': 1 if formState['includeMeta'] else 0,
}
)
response_data = response.json()
if response_data['code'] != 0:
print(response_data or '搜索失败')
return None
print(response_data)
return response_data['data']
except Exception as e:
print(e or '未知错误')
raise e
search()
import requests
import hashlib
import time
import random
formState = {
'content': '向量数据库的优势是什么',
'num': 1,
'includeMeta': False,
}
# 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
app_key = 'xxx' # 替换为自己的app_key
app_secret = 'xxx' # 替换为自己的app_secret
def getSignParams():
timestamp = str(int(time.time() * 1000))
nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))
# 对参数按key进行字典排序
params = {'app_key': app_key, 'app_secret': app_secret, 'timestamp': timestamp, 'nonce_str': nonce_str}
keys = sorted(params.keys())
_str = '&'.join([f'{key}={params[key]}' for key in keys])
# MD5加密
params['signature'] = hashlib.md5(_str.encode()).hexdigest()
return params
def search():
try:
response = requests.post(
url='https://api.yiruocloud.com/vector/search',
headers=getSignParams(),
json={
**formState,
'includeMeta': 1 if formState['includeMeta'] else 0,
}
)
response_data = response.json()
if response_data['code'] != 0:
print(response_data or '搜索失败')
return None
print(response_data)
return response_data['data']
except Exception as e:
print(e or '未知错误')
raise e
search()
Go
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
appKey = "xxx" // 替换为自己的app_key
appSecret = "xxx" // 替换为自己的app_secret
)
type FormState struct {
Content string `json:"content"`
Num int `json:"num"`
IncludeMeta bool `json:"includeMeta"`
}
type SearchResponse struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
func main() {
search()
}
func search() {
url := "https://api.yiruocloud.com/vector/search"
params := getSignParams()
formState := FormState{
Content: "向量数据库的优势是什么",
Num: 1,
IncludeMeta: false,
}
data := map[string]interface{}{
"content": formState.Content,
"num": formState.Num,
"includeMeta": boolToInt(formState.IncludeMeta),
}
req, err := http.NewRequest("POST", url, strings.NewReader(encodeParams(data)))
if err != nil {
fmt.Println(err)
return
}
for key, value := range params {
req.Header.Set(key, value)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
var searchResp SearchResponse
err = json.Unmarshal(body, &searchResp)
if err != nil {
fmt.Println(err)
return
}
if searchResp.Code != 0 {
fmt.Println("搜索失败")
return
}
fmt.Println(searchResp.Data)
}
func getSignParams() map[string]string {
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
nonceStr := getRandomString(8)
params := map[string]string{
"app_key": appKey,
"app_secret": appSecret,
"timestamp": timestamp,
"nonce_str": nonceStr,
}
keys := make([]string, 0, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var strBuilder strings.Builder
for _, key := range keys {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(params[key])
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
signature := md5Hash(str)
params["signature"] = signature
return params
}
func getRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
rand.Seed(time.Now().UnixNano())
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}
func encodeParams(data map[string]interface{}) string {
var strBuilder strings.Builder
for key, value := range data {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(fmt.Sprintf("%v", value))
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
return str
}
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
appKey = "xxx" // 替换为自己的app_key
appSecret = "xxx" // 替换为自己的app_secret
)
type FormState struct {
Content string `json:"content"`
Num int `json:"num"`
IncludeMeta bool `json:"includeMeta"`
}
type SearchResponse struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
func main() {
search()
}
func search() {
url := "https://api.yiruocloud.com/vector/search"
params := getSignParams()
formState := FormState{
Content: "向量数据库的优势是什么",
Num: 1,
IncludeMeta: false,
}
data := map[string]interface{}{
"content": formState.Content,
"num": formState.Num,
"includeMeta": boolToInt(formState.IncludeMeta),
}
req, err := http.NewRequest("POST", url, strings.NewReader(encodeParams(data)))
if err != nil {
fmt.Println(err)
return
}
for key, value := range params {
req.Header.Set(key, value)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
var searchResp SearchResponse
err = json.Unmarshal(body, &searchResp)
if err != nil {
fmt.Println(err)
return
}
if searchResp.Code != 0 {
fmt.Println("搜索失败")
return
}
fmt.Println(searchResp.Data)
}
func getSignParams() map[string]string {
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
nonceStr := getRandomString(8)
params := map[string]string{
"app_key": appKey,
"app_secret": appSecret,
"timestamp": timestamp,
"nonce_str": nonceStr,
}
keys := make([]string, 0, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var strBuilder strings.Builder
for _, key := range keys {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(params[key])
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
signature := md5Hash(str)
params["signature"] = signature
return params
}
func getRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
rand.Seed(time.Now().UnixNano())
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}
func encodeParams(data map[string]interface{}) string {
var strBuilder strings.Builder
for key, value := range data {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(fmt.Sprintf("%v", value))
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
return str
}
获取上传的临时授权凭证
js
const axios = require('axios');
const CryptoJS = require('crypto-js');
// 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
const app_key = 'xxx'; // 替换为自己的app_key
const app_secret = 'xxx'; // 替换为自己的app_secret
function getSignParams() {
const timestamp = Date.now().toString();
const nonce_str = Math.random().toString(36).substring(8);
// 对参数按key进行字典排序
const params = { app_key, app_secret, timestamp, nonce_str };
const keys = Object.keys(params).sort();
const str = keys.map((key) => `${key}=${params[key]}`).join('&');
// MD5加密
params.signature = CryptoJS.MD5(str).toString();
return params;
}
async function generateUploadToken() {
try {
const response = await axios({
url: 'https://api.yiruocloud.com/vector/generate-upload-token',
method: 'get',
headers: {
...getSignParams(),
},
});
if (response.data.code !== 0) {
console.error(response.data || '搜索失败');
return null;
}
console.log(response.data);
return response.data.data;
} catch (error) {
console.error(error.message || '未知错误');
throw error;
}
}
generateUploadToken();
const axios = require('axios');
const CryptoJS = require('crypto-js');
// 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
const app_key = 'xxx'; // 替换为自己的app_key
const app_secret = 'xxx'; // 替换为自己的app_secret
function getSignParams() {
const timestamp = Date.now().toString();
const nonce_str = Math.random().toString(36).substring(8);
// 对参数按key进行字典排序
const params = { app_key, app_secret, timestamp, nonce_str };
const keys = Object.keys(params).sort();
const str = keys.map((key) => `${key}=${params[key]}`).join('&');
// MD5加密
params.signature = CryptoJS.MD5(str).toString();
return params;
}
async function generateUploadToken() {
try {
const response = await axios({
url: 'https://api.yiruocloud.com/vector/generate-upload-token',
method: 'get',
headers: {
...getSignParams(),
},
});
if (response.data.code !== 0) {
console.error(response.data || '搜索失败');
return null;
}
console.log(response.data);
return response.data.data;
} catch (error) {
console.error(error.message || '未知错误');
throw error;
}
}
generateUploadToken();
Java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import okhttp3.*;
public class Main {
private static final String appKey = "xxx"; // 替换为自己的app_key
private static final String appSecret = "xxx"; // 替换为自己的app_secret
public static void main(String[] args) {
generateUploadToken();
}
private static void generateUploadToken() {
String url = "https://api.yiruocloud.com/vector/generate-upload-token";
Map<String, String> params = getSignParams();
OkHttpClient client = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.get();
for (Map.Entry<String, String> entry : params.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
Request request = requestBuilder.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.out.println("搜索失败");
return;
}
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception e) {
System.out.println("未知错误");
e.printStackTrace();
}
}
private static Map<String, String> getSignParams() {
String timestamp = String.valueOf(System.currentTimeMillis());
String nonceStr = getRandomString(8);
Map<String, String> params = new HashMap<>();
params.put("app_key", appKey);
params.put("app_secret", appSecret);
params.put("timestamp", timestamp);
params.put("nonce_str", nonceStr);
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
StringBuilder strBuilder = new StringBuilder();
for (String key : keys) {
strBuilder.append(key).append("=").append(params.get(key)).append("&");
}
String str = strBuilder.toString();
str = str.substring(0, str.length() - 1);
String signature = md5Hash(str);
params.put("signature", signature);
return params;
}
private static String getRandomString(int length) {
String charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rand = new Random();
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = rand.nextInt(charset.length());
strBuilder.append(charset.charAt(index));
}
return strBuilder.toString();
}
private static String md5Hash(String text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(text.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import okhttp3.*;
public class Main {
private static final String appKey = "xxx"; // 替换为自己的app_key
private static final String appSecret = "xxx"; // 替换为自己的app_secret
public static void main(String[] args) {
generateUploadToken();
}
private static void generateUploadToken() {
String url = "https://api.yiruocloud.com/vector/generate-upload-token";
Map<String, String> params = getSignParams();
OkHttpClient client = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.get();
for (Map.Entry<String, String> entry : params.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
Request request = requestBuilder.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.out.println("搜索失败");
return;
}
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception e) {
System.out.println("未知错误");
e.printStackTrace();
}
}
private static Map<String, String> getSignParams() {
String timestamp = String.valueOf(System.currentTimeMillis());
String nonceStr = getRandomString(8);
Map<String, String> params = new HashMap<>();
params.put("app_key", appKey);
params.put("app_secret", appSecret);
params.put("timestamp", timestamp);
params.put("nonce_str", nonceStr);
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
StringBuilder strBuilder = new StringBuilder();
for (String key : keys) {
strBuilder.append(key).append("=").append(params.get(key)).append("&");
}
String str = strBuilder.toString();
str = str.substring(0, str.length() - 1);
String signature = md5Hash(str);
params.put("signature", signature);
return params;
}
private static String getRandomString(int length) {
String charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rand = new Random();
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = rand.nextInt(charset.length());
strBuilder.append(charset.charAt(index));
}
return strBuilder.toString();
}
private static String md5Hash(String text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(text.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
Python
import requests
import hashlib
import time
import random
app_key = 'xxx' # 替换为自己的app_key
app_secret = 'xxx' # 替换为自己的app_secret
def get_sign_params():
timestamp = str(int(time.time() * 1000))
nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=8))
params = {
'app_key': app_key,
'app_secret': app_secret,
'timestamp': timestamp,
'nonce_str': nonce_str
}
keys = sorted(params.keys())
str_list = [f"{key}={params[key]}" for key in keys]
str = '&'.join(str_list)
signature = hashlib.md5(str.encode()).hexdigest()
params['signature'] = signature
return params
def generate_upload_token():
url = 'https://api.yiruocloud.com/vector/generate-upload-token'
headers = get_sign_params()
try:
response = requests.get(url, headers=headers)
response_data = response.json()
if response_data['code'] != 0:
print('搜索失败')
return None
print(response_data)
return response_data['data']
except Exception as e:
print('未知错误')
raise e
generate_upload_token()
import requests
import hashlib
import time
import random
app_key = 'xxx' # 替换为自己的app_key
app_secret = 'xxx' # 替换为自己的app_secret
def get_sign_params():
timestamp = str(int(time.time() * 1000))
nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=8))
params = {
'app_key': app_key,
'app_secret': app_secret,
'timestamp': timestamp,
'nonce_str': nonce_str
}
keys = sorted(params.keys())
str_list = [f"{key}={params[key]}" for key in keys]
str = '&'.join(str_list)
signature = hashlib.md5(str.encode()).hexdigest()
params['signature'] = signature
return params
def generate_upload_token():
url = 'https://api.yiruocloud.com/vector/generate-upload-token'
headers = get_sign_params()
try:
response = requests.get(url, headers=headers)
response_data = response.json()
if response_data['code'] != 0:
print('搜索失败')
return None
print(response_data)
return response_data['data']
except Exception as e:
print('未知错误')
raise e
generate_upload_token()
Golang
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
appKey = "xxx" // 替换为自己的app_key
appSecret = "xxx" // 替换为自己的app_secret
)
func main() {
generateUploadToken()
}
func generateUploadToken() {
url := "https://api.yiruocloud.com/vector/generate-upload-token"
params := getSignParams()
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("创建请求失败")
return
}
for key, value := range params {
req.Header.Add(key, value)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println("请求失败")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取响应失败")
return
}
fmt.Println(string(body))
}
func getSignParams() map[string]string {
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
nonceStr := getRandomString(8)
params := map[string]string{
"app_key": appKey,
"app_secret": appSecret,
"timestamp": timestamp,
"nonce_str": nonceStr,
}
keys := make([]string, 0, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var strBuilder strings.Builder
for _, key := range keys {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(params[key])
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
signature := md5Hash(str)
params["signature"] = signature
return params
}
func getRandomString(length int) string {
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
rand.Seed(time.Now().UnixNano())
strBuilder := strings.Builder{}
for i := 0; i < length; i++ {
index := rand.Intn(len(charset))
strBuilder.WriteByte(charset[index])
}
return strBuilder.String()
}
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
appKey = "xxx" // 替换为自己的app_key
appSecret = "xxx" // 替换为自己的app_secret
)
func main() {
generateUploadToken()
}
func generateUploadToken() {
url := "https://api.yiruocloud.com/vector/generate-upload-token"
params := getSignParams()
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("创建请求失败")
return
}
for key, value := range params {
req.Header.Add(key, value)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println("请求失败")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取响应失败")
return
}
fmt.Println(string(body))
}
func getSignParams() map[string]string {
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
nonceStr := getRandomString(8)
params := map[string]string{
"app_key": appKey,
"app_secret": appSecret,
"timestamp": timestamp,
"nonce_str": nonceStr,
}
keys := make([]string, 0, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var strBuilder strings.Builder
for _, key := range keys {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(params[key])
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
signature := md5Hash(str)
params["signature"] = signature
return params
}
func getRandomString(length int) string {
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
rand.Seed(time.Now().UnixNano())
strBuilder := strings.Builder{}
for i := 0; i < length; i++ {
index := rand.Intn(len(charset))
strBuilder.WriteByte(charset[index])
}
return strBuilder.String()
}
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
上传文件
js
const axios = require('axios');
const CryptoJS = require('crypto-js');
const formState = {
folderId: '',
url: '',
fileName: '',
description: '',
};
// 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
const app_key = 'xxx'; // 替换为自己的app_key
const app_secret = 'xxx'; // 替换为自己的app_secret
function getSignParams() {
const timestamp = Date.now().toString();
const nonce_str = Math.random().toString(36).substring(8);
// 对参数按key进行字典排序
const params = { app_key, app_secret, timestamp, nonce_str };
const keys = Object.keys(params).sort();
const str = keys.map((key) => `${key}=${params[key]}`).join('&');
// MD5加密
params.signature = CryptoJS.MD5(str).toString();
return params;
}
async function uploadFile() {
try {
const response = await axios({
url: 'https://api.yiruocloud.com/vector/upload-file',
method: 'post',
headers: {
...getSignParams(),
},
data: {
...formState,
},
});
if (response.data.code !== 0) {
console.error(response.data || '搜索失败');
return null;
}
console.log(response.data);
return response.data.data;
} catch (error) {
console.error(error.message || '未知错误');
throw error;
}
}
uploadFile();
const axios = require('axios');
const CryptoJS = require('crypto-js');
const formState = {
folderId: '',
url: '',
fileName: '',
description: '',
};
// 注意,不要将app_key和app_secret暴露在前端代码中,这里只是为了演示
const app_key = 'xxx'; // 替换为自己的app_key
const app_secret = 'xxx'; // 替换为自己的app_secret
function getSignParams() {
const timestamp = Date.now().toString();
const nonce_str = Math.random().toString(36).substring(8);
// 对参数按key进行字典排序
const params = { app_key, app_secret, timestamp, nonce_str };
const keys = Object.keys(params).sort();
const str = keys.map((key) => `${key}=${params[key]}`).join('&');
// MD5加密
params.signature = CryptoJS.MD5(str).toString();
return params;
}
async function uploadFile() {
try {
const response = await axios({
url: 'https://api.yiruocloud.com/vector/upload-file',
method: 'post',
headers: {
...getSignParams(),
},
data: {
...formState,
},
});
if (response.data.code !== 0) {
console.error(response.data || '搜索失败');
return null;
}
console.log(response.data);
return response.data.data;
} catch (error) {
console.error(error.message || '未知错误');
throw error;
}
}
uploadFile();
Java
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class Main {
private static final String appKey = "xxx"; // 替换为自己的app_key
private static final String appSecret = "xxx"; // 替换为自己的app_secret
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final Random random = new Random();
public static void main(String[] args) throws IOException {
uploadFile();
}
private static void uploadFile() throws IOException {
String url = "https://api.yiruocloud.com/vector/upload-file";
Map<String, String> params = getSignParams();
Map<String, String> headers = new HashMap<>(params);
RequestBody requestBody = RequestBody.create(JSON, "{\"folderId\":\"\",\"url\":\"\",\"fileName\":\"\",\"description\":\"\"}");
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.headers(Headers.of(headers))
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.out.println("请求失败");
return;
}
String responseBody = response.body().string();
System.out.println(responseBody);
}
}
private static Map<String, String> getSignParams() {
String timestamp = String.valueOf(System.currentTimeMillis());
String nonceStr = getRandomString(8);
Map<String, String> params = new TreeMap<>();
params.put("app_key", appKey);
params.put("app_secret", appSecret);
params.put("timestamp", timestamp);
params.put("nonce_str", nonceStr);
StringBuilder strBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
strBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
String str = strBuilder.toString();
str = str.substring(0, str.length() - 1);
String signature = DigestUtils.md5Hex(str);
params.put("signature", signature);
return params;
}
private static String getRandomString(int length) {
String charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = random.nextInt(charset.length());
strBuilder.append(charset.charAt(index));
}
return strBuilder.toString();
}
}
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class Main {
private static final String appKey = "xxx"; // 替换为自己的app_key
private static final String appSecret = "xxx"; // 替换为自己的app_secret
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final Random random = new Random();
public static void main(String[] args) throws IOException {
uploadFile();
}
private static void uploadFile() throws IOException {
String url = "https://api.yiruocloud.com/vector/upload-file";
Map<String, String> params = getSignParams();
Map<String, String> headers = new HashMap<>(params);
RequestBody requestBody = RequestBody.create(JSON, "{\"folderId\":\"\",\"url\":\"\",\"fileName\":\"\",\"description\":\"\"}");
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.headers(Headers.of(headers))
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.out.println("请求失败");
return;
}
String responseBody = response.body().string();
System.out.println(responseBody);
}
}
private static Map<String, String> getSignParams() {
String timestamp = String.valueOf(System.currentTimeMillis());
String nonceStr = getRandomString(8);
Map<String, String> params = new TreeMap<>();
params.put("app_key", appKey);
params.put("app_secret", appSecret);
params.put("timestamp", timestamp);
params.put("nonce_str", nonceStr);
StringBuilder strBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
strBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
String str = strBuilder.toString();
str = str.substring(0, str.length() - 1);
String signature = DigestUtils.md5Hex(str);
params.put("signature", signature);
return params;
}
private static String getRandomString(int length) {
String charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = random.nextInt(charset.length());
strBuilder.append(charset.charAt(index));
}
return strBuilder.toString();
}
}
Python
import requests
import hashlib
import time
import random
app_key = 'xxx' # 替换为自己的app_key
app_secret = 'xxx' # 替换为自己的app_secret
form_state = {
'folderId': '',
'url': '',
'fileName': '',
'description': '',
}
def get_sign_params():
timestamp = str(int(time.time() * 1000))
nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=8))
params = {
'app_key': app_key,
'app_secret': app_secret,
'timestamp': timestamp,
'nonce_str': nonce_str,
}
keys = sorted(params.keys())
str = '&'.join([f'{key}={params[key]}' for key in keys])
signature = hashlib.md5(str.encode()).hexdigest()
params['signature'] = signature
return params
def upload_file():
url = 'https://api.yiruocloud.com/vector/upload-file'
params = get_sign_params()
headers = {
**params,
}
response = requests.post(url, headers=headers, json=form_state)
if response.status_code != 200:
print('请求失败')
return None
data = response.json()
if data['code'] != 0:
print(data or '搜索失败')
return None
print(data)
return data['data']
upload_file()
import requests
import hashlib
import time
import random
app_key = 'xxx' # 替换为自己的app_key
app_secret = 'xxx' # 替换为自己的app_secret
form_state = {
'folderId': '',
'url': '',
'fileName': '',
'description': '',
}
def get_sign_params():
timestamp = str(int(time.time() * 1000))
nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=8))
params = {
'app_key': app_key,
'app_secret': app_secret,
'timestamp': timestamp,
'nonce_str': nonce_str,
}
keys = sorted(params.keys())
str = '&'.join([f'{key}={params[key]}' for key in keys])
signature = hashlib.md5(str.encode()).hexdigest()
params['signature'] = signature
return params
def upload_file():
url = 'https://api.yiruocloud.com/vector/upload-file'
params = get_sign_params()
headers = {
**params,
}
response = requests.post(url, headers=headers, json=form_state)
if response.status_code != 200:
print('请求失败')
return None
data = response.json()
if data['code'] != 0:
print(data or '搜索失败')
return None
print(data)
return data['data']
upload_file()
Golang
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
appKey = "xxx" // 替换为自己的app_key
appSecret = "xxx" // 替换为自己的app_secret
)
type FormState struct {
FolderId string `json:"folderId"`
URL string `json:"url"`
FileName string `json:"fileName"`
Description string `json:"description"`
}
func main() {
uploadFile()
}
func uploadFile() {
url := "https://api.yiruocloud.com/vector/upload-file"
params := getSignParams()
formState := FormState{
FolderId: "",
URL: "",
FileName: "",
Description: "",
}
client := &http.Client{}
req, err := http.NewRequest("POST", url, nil)
if err != nil {
fmt.Println("创建请求失败")
return
}
for key, value := range params {
req.Header.Add(key, value)
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("请求失败")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取响应失败")
return
}
fmt.Println(string(body))
}
func getSignParams() map[string]string {
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
nonceStr := getRandomString(8)
params := map[string]string{
"app_key": appKey,
"app_secret": appSecret,
"timestamp": timestamp,
"nonce_str": nonceStr,
}
keys := make([]string, 0, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var strBuilder strings.Builder
for _, key := range keys {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(params[key])
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
signature := md5Hash(str)
params["signature"] = signature
return params
}
func getRandomString(length int) string {
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
rand.Seed(time.Now().UnixNano())
strBuilder := strings.Builder{}
for i := 0; i < length; i++ {
index := rand.Intn(len(charset))
strBuilder.WriteByte(charset[index])
}
return strBuilder.String()
}
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
appKey = "xxx" // 替换为自己的app_key
appSecret = "xxx" // 替换为自己的app_secret
)
type FormState struct {
FolderId string `json:"folderId"`
URL string `json:"url"`
FileName string `json:"fileName"`
Description string `json:"description"`
}
func main() {
uploadFile()
}
func uploadFile() {
url := "https://api.yiruocloud.com/vector/upload-file"
params := getSignParams()
formState := FormState{
FolderId: "",
URL: "",
FileName: "",
Description: "",
}
client := &http.Client{}
req, err := http.NewRequest("POST", url, nil)
if err != nil {
fmt.Println("创建请求失败")
return
}
for key, value := range params {
req.Header.Add(key, value)
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("请求失败")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取响应失败")
return
}
fmt.Println(string(body))
}
func getSignParams() map[string]string {
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
nonceStr := getRandomString(8)
params := map[string]string{
"app_key": appKey,
"app_secret": appSecret,
"timestamp": timestamp,
"nonce_str": nonceStr,
}
keys := make([]string, 0, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var strBuilder strings.Builder
for _, key := range keys {
strBuilder.WriteString(key)
strBuilder.WriteString("=")
strBuilder.WriteString(params[key])
strBuilder.WriteString("&")
}
str := strBuilder.String()
str = str[:len(str)-1]
signature := md5Hash(str)
params["signature"] = signature
return params
}
func getRandomString(length int) string {
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
rand.Seed(time.Now().UnixNano())
strBuilder := strings.Builder{}
for i := 0; i < length; i++ {
index := rand.Intn(len(charset))
strBuilder.WriteByte(charset[index])
}
return strBuilder.String()
}
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}