当前位置: 首页 > article >正文

雷池社区版OPEN API使用教程

OPEN API使用教程

新版本接口支持API Token鉴权

image.png

接口文档官方没有提供,有需要可以自行爬取,爬了几个,其实也很方便

使用条件

  • 需要使用默认的 admin 用户登录才可见此功能
  • 版本需要 >= 6.6.0

使用方法

1.在系统管理创建API TOKEN image.png

2.发起请求,请求的header中增加额外的参数,如下

"X-SLCE-API-TOKEN": "雷池管理端生成的API Token"

案例参考

# python使用API Token添加站点案例

import requests
import json

header = {
    "X-SLCE-API-TOKEN": "雷池管理端生成的API Token"
}
#添加站点的URL
url = 'https://雷池IP:9443/api/open/site'

playload = {
    "ports":["80"],"server_names":["*"],
    "upstreams":["http://127.0.0.1:9443"],"comment":"",
    "load_balance":{"balance_type":1}
}

playload = json.dumps(playload)
requests.post(url=url,headers=header,data=playload,verify=False)


#go语言案例
package main

import (
    "bytes"
    "crypto/tls"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    url := "https://雷池IP:9443/api/open/site"
    token := "雷池管理端生成的API Token"

    payload := map[string]interface{}{
        "ports":         []string{"80"},
        "server_names":  []string{"*"},
        "upstreams":     []string{"http://127.0.0.1:9443"},
        "comment":       "",
        "load_balance":  map[string]int{"balance_type": 1},
    }

    jsonData, _ := json.Marshal(payload)

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        fmt.Println("Request error:", err)
        return
    }

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-SLCE-API-TOKEN", token)

    client := &http.Client{
        Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
    }
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("Response:", string(body))
}

# php 案例
<?php
$url = "https://雷池IP:9443/api/open/site";
$api_token = "雷池管理端生成的API Token";

$data = [
    "ports" => ["80"],
    "server_names" => ["*"],
    "upstreams" => ["http://127.0.0.1:9443"],
    "comment" => "",
    "load_balance" => ["balance_type" => 1]
];

$options = [
    "http" => [
        "header"  => [
            "Content-Type: application/json",
            "X-SLCE-API-TOKEN: $api_token"
        ],
        "method"  => "POST",
        "content" => json_encode($data),
        "ignore_errors" => true,
    ],
    "ssl" => [
        "verify_peer" => false,
        "verify_peer_name" => false,
    ]
];

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
echo $result;
?>

# java案例
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AddSite {
    public static void main(String[] args) {
        try {
            String url = "https://雷池IP:9443/api/open/site";
            String apiToken = "雷池管理端生成的API Token";

            String payload = """
                {
                    "ports": ["80"],
                    "server_names": ["*"],
                    "upstreams": ["http://127.0.0.1:9443"],
                    "comment": "",
                    "load_balance": {"balance_type": 1}
                }
                """;

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("X-SLCE-API-TOKEN", apiToken);
            con.setDoOutput(true);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = payload.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // Further code to read the response can be added here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
# node.js案例
const https = require('https');

const data = JSON.stringify({
    ports: ["80"],
    server_names: ["*"],
    upstreams: ["http://127.0.0.1:9443"],
    comment: "",
    load_balance: { balance_type: 1 }
});

const options = {
    hostname: '雷池IP',
    port: 9443,
    path: '/api/open/site',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-SLCE-API-TOKEN': '雷池管理端生成的API Token'
    },
    rejectUnauthorized: false
};

const req = https.request(options, (res) => {
    let data = '';
    res.on('data', (chunk) => { data += chunk; });
    res.on('end', () => { console.log('Response:', data); });
});

req.on('error', (e) => { console.error(e); });
req.write(data);
req.end();
#ruby案例
require 'net/http'
require 'uri'
require 'json'
require 'openssl'

url = URI("https://雷池IP:9443/api/open/site")
api_token = "雷池管理端生成的API Token"

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request["X-SLCE-API-TOKEN"] = api_token
request.body = {
  ports: ["80"],
  server_names: ["*"],
  upstreams: ["http://127.0.0.1:9443"],
  comment: "",
  load_balance: { balance_type: 1 }
}.to_json

response = http.request(request)
puts "Response:", response.read_body

大家可以结合熟悉的语言进行参考


http://www.kler.cn/a/369176.html

相关文章:

  • 【十六进制数转十进制数 】
  • SDK5(note中)
  • 优选算法精品课--双指针算法(2)
  • 创建ODBC数据源SQLConfigDataSource函数的用法
  • OSPF特殊区域及其他特性
  • maven之pom.xml文件解读
  • 模拟 DDoS 攻击与防御实验
  • 链表学习的疑惑
  • etcd之etcd分布式锁及事务(四)
  • [Web安全 网络安全]-反序列化漏洞
  • 【rabbitmq】rabbitmq工作模式
  • 震惊!25岁普信男又思索出自己的成功学?
  • 机器学习之 AdaBoost(Adaptive Boosting)
  • web相关知识学习笔记
  • MFC扩展库BCGControlBar Pro v35.1新版亮点 - 改进编辑控件性能
  • AI创作者与人类创作者的协作模式
  • 本地搭建Trilium Notes轻松创建个人知识库并实现远程查看文档资料
  • python 实现一个简单的浏览器引擎
  • Springboot整合原生ES依赖
  • 【力扣 + 牛客 | SQL题 | 每日3题】SQL大厂面试题SQL156, 157
  • 软考中级嵌入式系统设计师笔记分享(一)
  • Seatunnel和Seatunnel-web部署-linux
  • 【脚本】B站视频AB复读
  • 无人机之红外探测技术篇
  • [含文档+PPT+源码等]精品基于PHP实现的培训机构信息管理系统的设计与实现
  • 我用自研引擎做游戏:《干得好,托尼》