<div class="gda-row">
    <div class="gda-select">
        <select id="abilityCode" class="gda-select-selector">
            <option value="mattingcommon">通用抠图</option>
            <option value="mattingportrait">人像抠图</option>
            <option value="mattingproduct">商品抠图</option>
            <option value="mattinggraphs">图形抠图</option>
            <option value="passport">证件照抠图</option>
            <option value="portraitdetection">人像属性检测</option>
            <option value="typesetting">证件照排版</option>
            <option value="croptypesetting">证件照裁剪排版</option>
            <option value="watermark">图片加水印</option>
            <option value="inpaintblock">消除笔</option>
            <option value="cartoonportrait">卡通头像</option>
            <option value="imageanime">图像动漫化</option>
            <option value="styletransfer">风格迁移</option>
            <option value="faceedit">人脸编辑</option>
        </select>
    </div>

    <div class="gda-select">
        <select id="type" class="gda-select-selector">
            <option value="java">Java</option>
            <option value="python">Python</option>
            <option value="cpp">C++</option>
            <option value="php">php</option>
            <option value="nodejs">nodeJs</option>
        </select>
    </div>
</div>

<div class="gda-row">
    <input id="ak" class="gda-input" type="text" autocomplete="off" placeholder="AK">
    <input id="sk" class="gda-input" type="text" autocomplete="off" placeholder="SK">
    <input id="appId" class="gda-input" type="text" autocomplete="off" placeholder="APPID">
</div>

<div class="gda-row">
    <button type="button" class="gda-btn" onclick="copy()">一键复制代码</button>
    <span id="btnshow" style="visibility: hidden;color:#24b35f">复制成功!</span>
</div>
.gda-row {
    margin-bottom: 15px;
}

.gda-select {
    box-sizing: border-box;
    margin: 0;
    padding: 0 12px;
    min-width: 150px;
    color: #000000a6;
    font-size: 14px;
    line-height: 1.5;
    list-style: none;
    position: relative;
    display: inline-block;
    cursor: pointer;
    background-color: #fff;
    border: 1px solid #e8eaec;
    border-radius: 4px;
    transition: all .3s cubic-bezier(.645,.045,.355,1);
}

.gda-select-selector {
    position: relative;
    width: 100%;
    height: 40px;
    background-color: #fff;
    border: 0;
    outline: none;
}

.gda-input {
    width: 150px;
    height: 40px;
    padding: 0 12px;
    border: 1px solid #e8eaec;
    box-sizing: border-box;
    border-radius: 4px;
    transition: all .3s cubic-bezier(.645,.045,.355,1);
    outline: none;
}

.gda-input:focus {
    border-color: #2254f4;
}

.gda-btn {
    display: inline-block;
    height: 40px;
    padding: 8.5px 16px;
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    text-align: center;
    border: 0;
    border-radius: 4px;
    background: #2254f4;
    outline: 0;
    cursor: pointer;
    -webkit-appearance: button;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.gda-btn:active {
    opacity: .7;
}
var ak;
var sk;
var appId;
var abilityCode;
var type;
function copy() {
    ak = document.getElementById("ak").value;
    sk = document.getElementById("sk").value;
    appId = document.getElementById("appId").value;
    abilityCode = document.getElementById("abilityCode").value;
    type = document.getElementById("type").value;
    const textareaEle = document.createElement("textarea");
    document.body.appendChild(textareaEle);
    textareaEle.value = buildCode(type);
    textareaEle.select();
    textareaEle.readOnly = "readOnly";
    document.execCommand("copy");
    document.body.removeChild(textareaEle);
    document.getElementById("btnshow").style.visibility = "visible";
    messageHidden();
}

function messageHidden() {
    setTimeout(function () {
        document.getElementById("btnshow").style.visibility = "hidden";
    }, 1000);
}

function buildCode(type) {
    if (type == "java") {
        return buildJavaCode();
    }
    if (type == "python") {
        return buildPythonCode();
    }
    if (type == "cpp") {
        return buildCppCode();
    }
    if (type == "php") {
        return buildPhpCode();
    }
    if (type == "nodejs") {
        return buildNodeJsCode();
    }
}

function buildJavaCode() {
    return (
        "import com.alibaba.fastjson.JSONObject;\n" +
        "import org.apache.commons.codec.binary.Base64;\n" +
        "import org.apache.commons.lang3.StringUtils;\n" +
        "import org.apache.http.HttpEntity;\n" +
        "import org.apache.http.client.methods.CloseableHttpResponse;\n" +
        "import org.apache.http.client.methods.HttpPost;\n" +
        "import org.apache.http.entity.StringEntity;\n" +
        "import org.apache.http.impl.client.CloseableHttpClient;\n" +
        "import org.apache.http.impl.client.HttpClientBuilder;\n" +
        "import org.apache.http.util.EntityUtils;\n" +
        "import javax.crypto.Mac;\n" +
        "import javax.crypto.spec.SecretKeySpec;\n" +
        "import java.io.IOException;\n" +
        " \n" +
        "public class HashHmacTest {\n" +
        "    public static String getHMAC(String data, String key) throws Exception {\n" +
        '        String HMAC_SHA1_ALGORITHM = "HmacSHA1";\n' +
        "        SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);\n" +
        "        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);\n" +
        "        mac.init(signinKey);\n" +
        "        byte[] rawHmac = mac.doFinal(data.getBytes());\n" +
        "        return new String(Base64.encodeBase64(rawHmac));\n" +
        "    }\n" +
        "    public static void main(String[] args) throws Exception {\n" +
        '        String ak = "' +
        ak +
        '";\n' +
        '        String sk = "' +
        sk +
        '";\n' +
        '        String httpMethod = "POST";\n' +
        '        String uri = "/api/call/' +
        abilityCode +
        '/";\n' +
        '        String queryString = "";\n' +
        "        JSONObject jsonBody = new JSONObject();\n" +
        '        jsonBody.put("url", "你的图片地址");\n' +
        "        Long timestamp = System.currentTimeMillis() / 1000;\n" +
        '        String requestRaw = StringUtils.join(new String[]{httpMethod, "@", uri, "@", queryString, "@", timestamp.toString(), "@", jsonBody.toJSONString()}, "");\n' +
        "        String signature = getHMAC(requestRaw, sk);\n" +
        "        CloseableHttpClient client = HttpClientBuilder.create().build();\n" +
        '        HttpPost httpPost = new HttpPost("https://open-api.gaoding.com/api/call/' +
        abilityCode +
        '");\n' +
        "        CloseableHttpResponse response = null;\n" +
        "        try {\n" +
        '            httpPost.addHeader("Content-Type", "application/json");\n' +
        '            httpPost.addHeader("X-Timestamp", timestamp.toString());\n' +
        '            httpPost.addHeader("X-AccessKey", ak);\n' +
        '            httpPost.addHeader("X-Signature", signature);\n' +
        '            httpPost.addHeader("app_id", "' +
        appId +
        '");\n' +
        "            httpPost.setEntity(new StringEntity(jsonBody.toString()));\n" +
        "            response = client.execute(httpPost);\n" +
        "            HttpEntity responseEntity = response.getEntity();\n" +
        '            System.out.println("响应状态为:" + response.getStatusLine());\n' +
        "            if (responseEntity != null) {\n" +
        '                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));\n' +
        "            }\n" +
        "        } finally {\n" +
        "            try {\n" +
        "                // 释放资源\n" +
        "                if (client != null) {\n" +
        "                    client.close();\n" +
        "                }\n" +
        "                if (response != null) {\n" +
        "                    response.close();\n" +
        "                }\n" +
        "            } catch (IOException e) {\n" +
        "                e.printStackTrace();\n" +
        "            }\n" +
        "        }\n" +
        "    }\n" +
        "}"
    );
}

function buildPhpCode() {
    return (
        "<?php\n" +
        " \n" +
        '$ak = "' +
        ak +
        '";\n' +
        '$sk = "' +
        sk +
        '";\n' +
        '$appId = "' +
        appId +
        '";\n' +
        '$http_method="POST";\n' +
        '$uri = "/api/call/' +
        abilityCode +
        '/";\n' +
        '$query_string = "";\n' +
        "$time_stamp = time();\n" +
        '$dict_body=["url"=>"你的图片地址"];\n' +
        "$dict_str=json_encode($dict_body,true);\n" +
        '$request_raw = $http_method."@".$uri."@".$query_string."@".$time_stamp."@".$dict_str;\n' +
        "var_dump($request_raw);\n" +
        '$signature = hash_hmac("sha1",$request_raw, $sk,true);\n' +
        "$signature = base64_encode($signature);\n" +
        "var_dump($signature);\n" +
        "$headers=[\n" +
        '    "Content-Type:application/json",\n' +
        '    "X-Timestamp:".$time_stamp,\n' +
        '    "X-AccessKey:".$ak,\n' +
        '    "X-Signature:".$signature,\n' +
        '    "app_id:".$appId\n' +
        "];\n" +
        "$curl = curl_init();\n" +
        '$resquest_api = "https://open-api.gaoding.com/api/call/' +
        abilityCode +
        '";\n' +
        "curl_setopt($curl, CURLOPT_URL, $resquest_api);\n" +
        "curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);\n" +
        "curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n" +
        "curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);\n" +
        "curl_setopt($curl, CURLOPT_POST, 1);\n" +
        "curl_setopt($curl, CURLOPT_POSTFIELDS, $dict_str);\n" +
        "curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);\n" +
        "curl_setopt($curl, CURLOPT_NOBODY, FALSE);\n" +
        "$response = curl_exec($curl);\n" +
        "$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);\n" +
        "var_dump($status);\n" +
        "var_dump($response);\n" +
        "curl_close($curl);"
    );
}

function buildPythonCode() {
    return (
        "import json\n" +
        "import base64\n" +
        "import hmac\n" +
        "from hashlib import sha1\n" +
        "import requests\n" +
        "import time\n" +
        " \n" +
        "def hash_hmac(data, key, sha1):\n" +
        "    hmac_code = hmac.new(key.encode(), data.encode(), sha1).digest()\n" +
        "    return base64.b64encode(hmac_code).decode()\n" +
        " \n" +
        "if __name__ == '__main__':\n" +
        " \n" +
        '    ak = "' +
        ak +
        '"\n' +
        '    sk = "' +
        sk +
        '"\n' +
        '    http_method = "POST"\n' +
        '    uri = "/api/call/' +
        abilityCode +
        '/"\n' +
        '    query_string = ""\n' +
        "    time_stamp = str(int(time.time()))\n" +
        "    print(time_stamp)\n" +
        "    dict_body = {}\n" +
        '    dict_body["url"] = "你的图片地址"\n' +
        "    json_body = json.dumps(dict_body)\n" +
        '    list_raw = [http_method, "@", uri, "@", query_string, "@", time_stamp, "@", json_body]\n' +
        '    request_raw = "".join(list_raw)\n' +
        "    print(request_raw)\n" +
        "    signature = hash_hmac(request_raw, sk, sha1)\n" +
        "    print(signature)\n" +
        '    resquest_api = "https://open-api.gaoding.com/api/call/' +
        abilityCode +
        '"\n' +
        "    headers = {'Content-Type': 'application/json', 'X-Timestamp':time_stamp, 'X-AccessKey':ak, \"X-Signature\":signature,\"app_id\":\"" +
        appId +
        '"}\n' +
        "    resp = requests.post(resquest_api, headers=headers, data=json_body)\n" +
        "    code = resp.status_code\n" +
        "    print(code)\n" +
        "    resp_data = resp.text\n" +
        "    print(resp_data)"
    );
}

function buildCppCode() {
    return (
        "#include <iostream>\n" +
        "#include <curl/curl.h>\n" +
        "#include<json/json.h>\n" +
        "#include <time.h>\n" +
        "#include <string.h>\n" +
        '#include "hmac/hmac_hash.h"\n' +
        '#include "base64/base64.h"\n' +
        " \n" +
        "using namespace std;\n" +
        "// libcurl库下载链接:https://curl.haxx.se/download.html\n" +
        "// jsoncpp库下载链接:https://github.com/open-source-parsers/jsoncpp/\n" +
        "//base64 库下载链接 https://github.com/ReneNyffenegger/cpp-base64\n" +
        "//hmac 下载地址 https://blog.csdn.net/yasi_xi/article/details/9066003\n" +
        " \n" +
        'const static std::string strRequestUrl = "https://open-api.gaoding.com/api/call/' +
        abilityCode +
        '";\n' +
        "static std::string segPersonResult;\n" +
        " \n" +
        "/**\n" +
        " * curl发送http请求调用的回调函数,回调函数中对返回的json格式的body进行了解析,解析结果储存在全局的静态变量当中\n" +
        " * @param 参数定义见libcurl文档\n" +
        " * @return 返回值定义见libcurl文档\n" +
        " */\n" +
        "static size_t callback(void *ptr, size_t size, size_t nmemb, void *stream)\n" +
        "{\n" +
        "    // 获取到的body存放在ptr中,先将其转换为string格式\n" +
        "    segPersonResult = std::string((char *) ptr, size * nmemb);\n" +
        "    return size * nmemb;\n" +
        "}\n" +
        " \n" +
        "int segPerson(std::string &strJsonResult,std::string &strJsonBody,std::string &strAccessKey,std::string &strTimeStamp,std::string & strEncoded,std::string & appId)\n" +
        "{\n" +
        "    std::string url = strRequestUrl;\n" +
        "    CURL *pCurl = NULL;\n" +
        "    struct curl_slist* pHeaders = NULL; \n" +
        "    CURLcode nResultCode;\n" +
        "    int nSuccess;\n" +
        "    pCurl = curl_easy_init();\n" +
        "    if (pCurl)\n" +
        "    {\n" +
        "        //设置请求头\n" +
        '        string strHeadTimeStap = "X-Timestamp: "+strTimeStamp;\n' +
        '        string strHeadAk = "X-AccessKey: "+strAccessKey;\n' +
        '        string strHeadSn = "X-Signature: "+strEncoded;\n' +
        '        string appId = "app_id: "+appId;\n' +
        " \n" +
        '        pHeaders = curl_slist_append(pHeaders,"content-type:application/json");\n' +
        "        pHeaders = curl_slist_append(pHeaders, strHeadTimeStap.c_str());\n" +
        "        pHeaders = curl_slist_append(pHeaders, strHeadAk.c_str());\n" +
        "        pHeaders = curl_slist_append(pHeaders, strHeadSn.c_str());\n" +
        "        pHeaders = curl_slist_append(pHeaders, appId.c_str());\n" +
        "        curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, pHeaders);\n" +
        "        curl_easy_setopt(pCurl, CURLOPT_URL, url.data());\n" +
        "        curl_easy_setopt(pCurl, CURLOPT_POST, 1);\n" +
        "        curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, strJsonBody.c_str());\n" +
        "        curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, callback);\n" +
        "        nResultCode = curl_easy_perform(pCurl);\n" +
        "        if (nResultCode != CURLE_OK)\n" +
        "        {\n" +
        '            fprintf(stderr, "curl_easy_perform() failed: %s\\n",\n' +
        "                    curl_easy_strerror(nResultCode));\n" +
        "            nSuccess = 1;\n" +
        "            return nSuccess;\n" +
        "        }\n" +
        "        strJsonResult = segPersonResult;\n" +
        "        curl_easy_cleanup(pCurl);\n" +
        "        nSuccess = 0;\n" +
        "    }\n" +
        "    else\n" +
        "    {\n" +
        '        fprintf(stderr, "curl_easy_init() failed.");\n' +
        "        nSuccess = 1;\n" +
        "    }\n" +
        "    return nSuccess;\n" +
        "}\n" +
        " \n" +
        "int main()\n" +
        "{\n" +
        "    Json::Reader reader;\n" +
        "    Json::Value reqData;\n" +
        '    string strAccessKey = "' +
        ak +
        '";\n' +
        '    string strSecretkey = "' +
        sk +
        '";\n' +
        '    string appId = "' +
        appId +
        '";\n' +
        '    string strHttpMethod = "POST";\n' +
        '    string strUri = "/api/call/' +
        abilityCode +
        '/";\n' +
        '    string strQueryString = "";\n' +
        "    // 选择加密方式为sha1\n" +
        '    string strAlg = "sha1";\n' +
        "    time_t lt = time(NULL);\n" +
        "    string strTimeStamp = std::to_string(int(lt));\n" +
        " \n" +
        "    // TODO 使用真实接口入参\n" +
        '    reqData["url"] = Json::Value("你的图片地址");\n' +
        "    std::string strJsonBody = reqData.toStyledString();\n" +
        " \n" +
        '    string strRequestRaw = strHttpMethod + "@" + strUri + "@" + strQueryString + "@" + strTimeStamp +"@" +strJsonBody ;\n' +
        " \n" +
        "    unsigned char * pMac = NULL;\n" +
        "    unsigned int nMacLength= 0;\n" +
        "    //hsmc - sha1加密\n" +
        "    int ret = HmacEncode(strAlg.c_str(), strSecretkey.c_str(), strSecretkey.length(), strRequestRaw.c_str(), strRequestRaw.length(), pMac, nMacLength);\n" +
        "    // base64 编码\n" +
        "    std::string strEncoded = base64_encode(reinterpret_cast<const unsigned char*>(pMac), nMacLength);\n" +
        "    //取出结果\n" +
        '    std::string strResult = "";\n' +
        "    int nCode = segPerson(strResult,strJsonBody,strAccessKey,strTimeStamp,strEncoded,appId);\n" +
        "    cout<<strResult<<endl;\n" +
        "    return 0;\n" +
        "}"
    );
}

function buildNodeJsCode() {
    return (
        "const axios = require('axios');\n" +
        "const {\n" +
        "    createHmac\n" +
        "} = require('crypto');\n" +
        "\n" +
        "axios.defaults.baseURL = 'https://open-api.gaoding.com';\n" +
        "axios.interceptors.request.use(async (config) => {\n" +
        "    const timestamp = Math.floor(Date.now() / 1000);\n" +
        "    const ak = '" +
        ak +
        "';\n" +
        "    const sk = '" +
        sk +
        "';\n" +
        "    config.headers['x-AccessKey'] = ak;\n" +
        "    config.headers['x-Timestamp'] = timestamp;\n" +
        "    let canonicalRequest = `${config.method.toUpperCase()}@${(config.url + '/').replace(\n" +
        "        /\\/\\/$/,\n" +
        "        '/',\n" +
        "    )}`;\n" +
        "    if (config.params) {\n" +
        "        const qs = Object.keys(config.params || {})\n" +
        "            .sort()\n" +
        "            .map((k) => `${k}=${config.params[k]}`)\n" +
        "            .join('&');\n" +
        "        canonicalRequest += `@${qs}`;\n" +
        "    } else {\n" +
        "        canonicalRequest += '@';\n" +
        "    }\n" +
        "    canonicalRequest += `@${timestamp}`;\n" +
        "    if (config.data) {\n" +
        "        canonicalRequest += `@${JSON.stringify(config.data)}`;\n" +
        "    }\n" +
        "    config.headers['x-Signature'] = createHmac('sha1', sk)\n" +
        "        .update(canonicalRequest)\n" +
        "        .digest('base64');\n" +
        "    config.headers['app_id'] = \"" +
        appId +
        '"\n' +
        "    return config;\n" +
        "});\n" +
        "\n" +
        "axios.interceptors.response.use(function (response) {\n" +
        "    console.log(response.data)\n" +
        "    return response;\n" +
        "}, function (error) {\n" +
        "    return Promise.reject(error);\n" +
        "});\n" +
        "axios.post('/api/call/" +
        abilityCode +
        "/',{\n" +
        '    url: "你的图片地址"\n' +
        "})\n"
    );
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.