Java 开发参考
import java.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HellorfSDK {
private String client_id; // 客户端ID
private String client_secret; // 客户端密钥
public HellorfSDK(String client_id, String client_secret) { // 构造函数,传入客户端ID和密钥参数
this.client_id = client_id;
this.client_secret = client_secret;
}
// GET请求方法,传入请求的endpoint被哪个资源所使用,以及其他自定义参数$params
public String get(String endpoint, Map<String, String> params) {
return request("GET", endpoint, params);
}
// POST请求方法,传入请求的endpoint被哪个资源所使用,以及其他自定义参数$params
public String post(String endpoint, Map<String, String> params) {
return request("POST", endpoint, params);
}
// 请求方法,用于HTTP请求
private String request(String method, String endpoint, Map<String, String> params) throws Exception {
params.put("nonce_str", String.valueOf(System.currentTimeMillis()/1000)); // 随机数参数,确保每个请求具有唯一性
params.put("client_id", this.client_id);
params.put("sign", makeSign(params)); // 在传递给API之前,生成签名作为身份验证标志
String url = "https://api.hellorf.com/plus/" + endpoint;
HttpClient client = HttpClients.createDefault();
if (method.equals("POST")) { // POST请求方式
HttpPost postRequest = new HttpPost(url); // 创建HTTP Post请求对象
postRequest.setHeader("Content-Type", "application/json"); // 设置请求头部
StringEntity requestBody = new StringEntity(new Gson().toJson(params)); // 将参数转换为json格式
postRequest.setEntity(requestBody); // 设置请求数据体
HttpResponse response = client.execute(postRequest); // 发送请求并获取响应
int statusCode = response.getStatusLine().getStatusCode(); // 获取响应码
String responseBody = EntityUtils.toString(response.getEntity()); // 获取响应体
if (statusCode != 200) { // 如果API响应码不是200,即失败
throw new Exception("Failed to retrieve data from API: " + responseBody); // 抛出异常
}
return responseBody; // 返回API响应体
} else if (method.equals("GET")) { // GET请求方式
if (!params.isEmpty()) {
url += "?" + buildQueryString(params);
}
HttpGet getRequest = new HttpGet(url); // 创建HTTP Get请求对象
HttpResponse response = client.execute(getRequest); // 发送请求并获取响应
int statusCode = response.getStatusLine().getStatusCode(); // 获取响应码
String responseBody = EntityUtils.toString(response.getEntity()); // 获取响应体
if (statusCode != 200) { // 如果API响应码不是200,即失败
throw new Exception("Failed to retrieve data from API: " + responseBody); // 抛出异常
}
return responseBody; // 返回API响应体
} else {
throw new Exception("Unsupported method!");
}
}
// 自定义方法来构建HTTP URL格式的查询字符串
public static String buildQueryString(Map<String, String> params) {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (result.length() > 0) {
result.append("&");
}
try {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding not supported", e);
}
}
return result.toString();
}
private String makeSign(Map<String, String> params) {
//从参数中移除 sign 和 file 两个参数
params.remove("sign");
params.remove("file");
//对参数按照字母升序排序
String[] sortedKeys = params.keySet().toArray(new String[0]);
Arrays.sort(sortedKeys);
//生成待签名字符串
StringBuilder builder = new StringBuilder();
for (String key : sortedKeys) {
builder.append(key).append("=").append(params.get(key)).append("&");
}
builder.append("client_secret=").append(this.client_secret);
String unsignedStr = builder.toString();
//使用 MD5 进行签名运算
String signature = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(unsignedStr.getBytes());
StringBuilder sigBuilder = new StringBuilder();
for (byte b : bytes) {
sigBuilder.append(Integer.toHexString((b >> 4) & 0xf)).append(Integer.toHexString(b & 0xf));
}
signature = sigBuilder.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to generate signature", e);
}
return signature;
}
}
Java 调用示例
String client_id = "your_client_id";
String client_secret = "your_client_secret";
// 在实例化 HellorfSDK 对象时传入客户端 ID 和密钥
HellorfSDK hellorfSdk = new HellorfSDK(client_id, client_secret);
// 调用 GET 接口,传入 API 的 endpoint 和自定义参数
Map<String, String> getParams = new HashMap<>();
getParams.put("key1", "value1");
getParams.put("key2", "value2");
try {
String response = hellorfSdk.get("image/search", getParams);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
// 调用 POST 接口,传入 API 的 endpoint 和自定义参数
Map<String, String> postParams = new HashMap<>();
postParams.put("key1", "value1");
postParams.put("key2", "value2");
try {
String response = hellorfSdk.post("image/simi-search", postParams);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
Go 开发参考
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strconv"
"time"
)
type HellorfSDK struct {
clientID string
clientSecret string
}
func HellorfSDK(clientID, clientSecret string) *HellorfSDK {
return &HellorfSDK{
clientID: clientID,
clientSecret: clientSecret,
}
}
func (h *HellorfSDK) Get(endpoint string, params url.Values) ([]byte, error) {
reqURL := fmt.Sprintf("https://api.hellorf.com/plus/%s", endpoint)
return h.request(http.MethodGet, reqURL, params)
}
func (h *HellorfSDK) Post(endpoint string, params map[string]interface{}) ([]byte, error) {
reqURL := fmt.Sprintf("https://api.hellorf.com/plus/%s", endpoint)
bs, err := json.Marshal(params)
if err != nil {
return nil, err
}
formattedParams := url.Values{}
formattedParams.Add("data", string(bs))
return h.request(http.MethodPost, reqURL, formattedParams)
}
func (h *HellorfSDK) request(method, urlStr string, params url.Values) ([]byte, error) {
params.Set("nonce_str", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("client_id", h.clientID)
params.Set("sign", h.makeSign(params))
req, err := http.NewRequest(method, urlStr, nil)
if err != nil {
return nil, err
}
switch method {
case http.MethodGet:
req.URL.RawQuery = params.Encode()
case http.MethodPost:
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.PostForm = params
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Failed to retrieve data from API: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (h *HellorfSDK) makeSign(params url.Values) string {
delete(params, "sign")
delete(params, "file")
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var str string
for _, k := range keys {
str += k + "=" + params.Get(k) + "&"
}
str += "client_secret=" + h.clientSecret
hash := md5.Sum([]byte(str))
sign := fmt.Sprintf("%x", hash)
return sign
}
Go 调用示例
clientID := "your_client_id"
clientSecret := "your_client_secret"
hellorf := HellorfSDK(clientID, clientSecret)
// GET请求示例
params := url.Values{}
params.Set("param1", "value1")
params.Set("param2", "value2")
response, err := hellorf.Get("image/search", params)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", response)
// POST请求示例
params = url.Values{}
params.Set("field1", "value1")
params.Set("field2", "value2")
response, err = hellorf.Post("image/simi-search", params)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", response)
PHP 开发参考
class HellorfSDK
{
private $client_id; // 客户端ID
private $client_secret; // 客户端密钥
public function __construct($client_id, $client_secret) // 构造函数,传入客户端ID和密钥参数
{
$this->client_id = $client_id;
$this->client_secret = $client_secret;
}
// GET请求方法,传入请求的endpoint被哪个资源所使用,以及其他自定义参数$params
public function get($endpoint, $params)
{
$this->request("GET", $endpoint, $params);
}
// POST请求方法,传入请求的endpoint被哪个资源所使用,以及其他自定义参数$params
public function post($endpoint, $params)
{
$this->request("POST", $endpoint, $params);
}
// 请求方法,用于HTTP请求
private function request($method, $endpoint, $params)
{
$params['sign'] = $this->makeSign($params); // 在传递给API之前,生成签名作为身份验证标志
$params['client_id'] = $this->client_id;
$params['nonce_str'] = time(); // 随机数参数,确保每个请求具有唯一性
$response = $this->makeRequest($method, "https://example.com/api/" . $endpoint, $params); // 通过调用 $this->makeRequest() 发送请求
if ($response["status_code"] != 200) { // 如果API响应码不是200,即失败
throw new \Exception("Failed to retrieve data from API: " . $response["body"]); // 抛出异常
}
return $response["body"]; // 返回API响应体
}
private function makeSign($params)
{ // 实例方法,生成签名
unset($params['sign']);
unset($params['file']);
ksort($params); // 按照参数字典序排序
$str = http_build_query($params);
$md5_str = urldecode($str);
return md5($md5_str . '&client_secret=' . $this->client_secret); // 在拼接好的参数字符串后面加上客户端密钥,并利用MD5算法生成签名
}
private function makeRequest($method, $url, $params = array())
{
// 用于发出 HTTP 请求的通用方法
$ch = curl_init();
if ($method == "POST") { // POST请求方式
curl_setopt($ch, CURLOPT_POST, true); // 启用POST请求方式
if (count($params) > 0) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); // POST请求参数为json格式
}
} else if ($method == "GET") { // GET请求方式
if (count($params) > 0) {
$url .= "?" . http_build_query($params); // 拼接GET请求参数
}
}
curl_setopt($ch, CURLOPT_URL, $url); // 设置请求URL
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json")); // 设置请求头部
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回值为字符串
$response_body = curl_exec($ch); // 执行请求,获取响应体
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 获取响应码
curl_close($ch); // 关闭curl句柄
return array(
"status_code" => $response_code, // 响应信息数组,包括状态码和返回数据体(json格式)
"body" => json_decode($response_body, true), // 转化成关联数组格式
);
}
}
PHP 调用示例
$client_id = "your_client_id";
$client_secret = "your_client_secret";
$hellorf = new HellorfSDK($client_id, $client_secret);
// GET请求示例
$params = array(
"param1" => "value1",
"param2" => "value2",
);
try {
$response = $hellorf->get("image/search", $params);
var_dump($response);
} catch (Exception e) {
throw new \Exception("Failed"); // 抛出异常
}
// POST请求示例
$params = array(
"field1" => "value1",
"field2" => "value2",
);
try {
$response = $hellorf->post("image/simi-search", $params);
var_dump($response);
} catch (Exception e) {
throw new \Exception("Failed"); // 抛出异常
}