<?php
function callApi($url, $method, $data = []) {
$ch = curl_init();
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
} else if ($method == 'GET' && !empty($data)) {
$url .= '?' . http_build_query($data);
curl_setopt($ch, CURLOPT_URL, $url);
}
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
// 使用示例
$apiUrl = 'https://api.okcode.vip/api/dev/example';
$params = [
'key' => '你的接口密钥,登录控制台后在密钥管理页面申请',
'param1' => 'a'
];
//调用GET接口
$result = callApi($apiUrl, 'GET', $params);
print_r(json_decode($result, true));
//调用POST接口
$result = callApi($apiUrl, 'POST', $params);
print_r(json_decode($result, true));
import requests
url = 'https://api.okcode.vip/api/dev/example'
response = requests.post(url, data={'key': '你的接口密钥,登录控制台后在密钥管理页面申请', 'param1': 'value2'})
result = response.json()
print(result)
//jQuery-Ajax
$.ajax({
url: 'https://api.okcode.vip/api/dev/example',
data: {
key: '你的接口密钥,登录控制台后在密钥管理页面申请',
参数名: '参数值',
},
type: 'POST',
dataType: 'json',
success: function(data) {
console.log(data); //请求成功,输出结果到控制台
},
timeout: 3000, //超时时间
error: function(data) {
console.log('请求失败'); //失败处理
}
});
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {
public static void main(String[] args) {
try {
URL url = new URL("https://api.okcode.vip/api/dev/example?key=你的接口密钥,登录控制台后在密钥管理页面申请");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// 设置请求方式
connection.setRequestMethod("GET");
connection.connect();
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
// 读取到的内容给line变量
System.out.println(line);
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// 发起一个GET请求
resp, err := http.Get("https://api.okcode.vip/api/dev/example?key=你的接口密钥,登录控制台后在密钥管理页面申请")
if err != nil {
fmt.Println("http get error", err)
return
}
// 读取响应结果
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("http read error", err)
return
}
// 关闭响应结果
defer resp.Body.Close()
fmt.Println(string(result))
}