附录-示例代码

示例代码说明

        以下多种语言代码仅供参考,不建议直接复制使用,需要结合实际业务情况进行处理,为了示例方便,以下代码均使用同一个择吉日接口,密钥已做脱敏处理。

PHP代码示例(POST)

                        
//您的密钥
$api_secret = "wD******XhOUW******pvr";
//请求择日择时接口
$gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

//请求参数
$request_data = [
    'api_key' => $api_secret,
    'future' => '0',
    'incident' => '3',
];

//curl
function curlSend($process_gateway, $data_arr, $type = 1) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $process_gateway);
    curl_setopt($ch, CURLOPT_POST, $type);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data_arr));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_FAILONERROR, true); // Set this option to handle errors

    $response = curl_exec($ch);

    if ($response === false) {
        $error_message = curl_error($ch);
        // Handle or output the error message as needed
        echo "cURL error: " . $error_message;
    }

    curl_close($ch);
    return $response;
}

function process_host($curlPost,$gateway_url) {
    $response = curlSend($gateway_url,$curlPost,1);
    print_r($response);

}

process_host($request_data,$gateway_host_url);
                        
                    

PHP代码示例(GET)

                        
//您的密钥
$api_secret = "wD******XhOUW******pvr";

//请求择日择时接口
$gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

//目标页面的URL
$url = $gateway_host_url. "?" . "api_key=" . $api_secret . "&future=0" . "&incident=3";

// 使用 cURL 的错误处理
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 禁用 SSL 证书验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$content = curl_exec($ch);

if (curl_errno($ch)) {
    // 打印 cURL 错误信息
    echo 'Curl error: ' . curl_error($ch);
} else {
    // 打印返回结果
    echo $content;
}

curl_close($ch);
                        
                    

Python代码示例

                        
import requests

# 您的密钥
api_secret = "wD******XhOUW******pvr"
# 请求择日择时接口
gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi"

# 请求参数
request_data = {
    'api_key': api_secret,
    'future': '0',
    'incident': '3',
}

def process_host(data, url):
    try:
        response = requests.post(url, data=data)
        response.raise_for_status()  # Raise an HTTPError for bad responses
        print(response.text)
    except requests.exceptions.RequestException as e:
        # Handle or output the error message as needed
        print(f"Request error: {e}")

process_host(request_data, gateway_host_url)
                        
                    

Java代码示例

                        
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Your API secret
        String apiSecret = "wD******XhOUW******pvr";

        // API endpoint URL
        String gatewayHostUrl = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

        // Request parameters
        Map< String, String> requestData = Map.of(
                "api_key", apiSecret,
                "future", "0",
                "incident", "3"
        );

        // Process the request
        processHost(requestData, gatewayHostUrl);
    }

    private static void processHost(Map< String, String> postData, String gatewayUrl) {
        try {
            URL url = new URL(gatewayUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Enable input/output streams
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // Set request method to POST
            connection.setRequestMethod("POST");

            // Build POST data
            StringBuilder postDataStringBuilder = new StringBuilder();
            for (Map.Entry< String, String> entry : postData.entrySet()) {
                if (postDataStringBuilder.length() != 0) {
                    postDataStringBuilder.append('&');
                }
                postDataStringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                postDataStringBuilder.append('=');
                postDataStringBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }

            // Write POST data to connection
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] postDataBytes = postDataStringBuilder.toString().getBytes("UTF-8");
                outputStream.write(postDataBytes);
                outputStream.flush();
            }

            // Get response
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder responseStringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    responseStringBuilder.append(line);
                }
                System.out.println(responseStringBuilder.toString());
            }

            // Close connection
            connection.disconnect();

        } catch (IOException e) {
            // Handle or output the error message as needed
            e.printStackTrace();
        }
    }
}
                        
                    

Node.js代码示例

                        
const axios = require('axios');
const qs = require('qs');

// 您的密钥
const api_secret = "wD******XhOUW******pvr";
// 请求择日择时接口
const gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

// 请求参数
const request_data = {
    api_key: api_secret,
    future: '0',
    incident: '3',
};

// 发送请求的函数
async function sendRequest(url, data) {
    try {
        const response = await axios.post(url, qs.stringify(data), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        });
        console.log(response.data);
    } catch (error) {
        if (error.response) {
            // 服务器返回一个状态码范围在2xx之外
            console.error('Response error:', error.response.status, error.response.data);
        } else if (error.request) {
            // 请求已发送但没有收到响应
            console.error('No response received:', error.request);
        } else {
            // 设置请求时发生错误
            console.error('Error setting up request:', error.message);
        }
    }
}

// 执行请求
sendRequest(gateway_host_url, request_data);

                        
                    

Javascript代码示例

                        
// 您的密钥
const apiSecret = "wD******XhOUW******pvr";
// 请求择日择时接口
const gatewayHostUrl = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

// 请求参数
const requestData = {
    api_key: apiSecret,
    future: '0',
    incident: '3',
};

// fetch 函数的 JavaScript 实现
async function fetchSend(processGateway, dataObj, type = 'POST') {
    try {
        const response = await fetch(processGateway, {
            method: type,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(dataObj),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        return await response.text();
    } catch (error) {
        // Handle or output the error message as needed
        console.error(`Fetch error: ${error.message}`);
        return null;
    }
}

// processHost 函数的 JavaScript 实现
async function processHost(curlPost, gatewayUrl) {
    const response = await fetchSend(gatewayUrl, curlPost);
    if (response !== null) {
        console.log(response);
    }
}

// 调用 processHost 函数
processHost(requestData, gatewayHostUrl);
                        
                    

Go代码示例

                        
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	// 您的密钥
	apiSecret := "wD******XhOUW******pvr"

	// 请求择日择时接口
	gatewayHostURL := "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi"

	// 请求参数
	apiKey := apiSecret
	future := "0"
	incident := "3"

	// 构造请求参数
	requestData := fmt.Sprintf("api_key=%s&future=%s&incident=%s", apiKey, future, incident)

	// 发送请求并打印响应
	response, err := sendRequest(gatewayHostURL, requestData)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(response)
}

func sendRequest(processGateway, data string) (string, error) {
	resp, err := http.Post(processGateway, "application/x-www-form-urlencoded", bytes.NewBufferString(data))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body), nil
}
                        
                    

C#代码示例

                        
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // 您的密钥
        string api_secret = "wD******XhOUW******pvr";

        // 请求择日择时接口
        string gateway_host_url = "https://api.yuanfenju.com/index.php/v1/Gongju/zeshi";

        // 请求参数
        string api_key = api_secret;
        string future = "0";
        string incident = "3";

        // 构造请求参数
        string request_data = $"api_key={api_key}&future={future}&incident={incident}";

        // 发送请求并打印响应
        string response = await SendRequestAsync(gateway_host_url, request_data);
        Console.WriteLine(response);
    }

    static async Task< string> SendRequestAsync(string process_gateway, string data)
    {
        using (HttpClient client = new HttpClient())
        {
            // 发送 POST 请求
            HttpResponseMessage httpResponse = await client.PostAsync(process_gateway, new StringContent(data));

            // 读取响应内容
            string response = await httpResponse.Content.ReadAsStringAsync();
            return response;
        }
    }
}