文本离线结果获取

接口地址

https://as.dun.163yun.com/v3/text/callback/results

接口描述

在线检测接口结果中嫌疑的数据,会进行离线分析和人工审核,这些数据的离线结果需要客户通过该接口进行定时获取。获取离线处理的数据后,下次调用,不会再次返回之前获取过的离线数据。接口对请求频率做了限制,请求频率过快服务器会拒绝处理,建议30秒获取一次。

请求参数

该接口参数与请求公共参数一致,详细见 请求公共参数

响应结果

响应字段如下,响应通用字段已省略,详细见 响应通用字段

result 数组数据结构

参数名称类型描述
actionNumber检测结果,0:通过,2:不通过
taskIdString在线接口检测返回的数据请求标识,可以根据该标识查询数据最新结果
callbackString产品调用文本在线检测传递的 callback 字段数据。
labelsjson数组分类信息

labels 数据结构

参数名称类型描述
labelNumber分类信息,100:色情,200:广告,400:违禁,500:涉政,600:谩骂,700:灌水
levelNumber分类级别,1:不确定,2:确定
detailsjson对象其他信息

details 数据结构

参数名称类型描述
hintjson数组线索信息,用于定位文本中有问题的部分,辅助人工审核

请求示例

    /** 产品密钥ID,产品标识 */
    private final static String SECRETID = "your_secret_id";
    /** 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露 */
    private final static String SECRETKEY = "your_secret_key";
    /** 业务ID,易盾根据产品业务特点分配 */
    private final static String BUSINESSID = "your_business_id";
    /** 易盾内容安全服务文本离线检测结果获取接口地址 */
    private final static String API_URL = "https://as.dun.163yun.com/v3/text/callback/results";
    /** 实例化HttpClient,发送http请求使用,可根据需要自行调参 */
    private static HttpClient httpClient = HttpClient4Utils.createHttpClient(100, 20, 10000, 2000, 2000);

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        // 1.设置公共参数
        params.put("secretId", SECRETID);
        params.put("businessId", BUSINESSID);
        params.put("version", "v3.1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("nonce", String.valueOf(new Random().nextInt()));

        // 2.生成签名信息
        String signature = SignatureUtils.genSignature(SECRETKEY, params);
        params.put("signature", signature);

        // 3.发送HTTP请求,这里使用的是HttpClient工具包,产品可自行选择自己熟悉的工具包发送请求
        String response = HttpClient4Utils.sendPost(httpClient, API_URL, params, Consts.UTF_8);

        // 4.解析接口返回值
        JsonObject resultObject = new JsonParser().parse(response).getAsJsonObject();
        int code = resultObject.get("code").getAsInt();
        String msg = resultObject.get("msg").getAsString();
        if (code == 200) {
            JsonArray resultArray = resultObject.getAsJsonArray("result");
            if (resultArray.size() == 0) {
                System.out.println("暂时没有人工复审结果需要获取,请稍后重试!");
            }
            for (JsonElement jsonElement : resultArray) {
                JsonObject jObject = jsonElement.getAsJsonObject();
                int action = jObject.get("action").getAsInt();
                String taskId = jObject.get("taskId").getAsString();
                String callback = jObject.get("callback").getAsString();
                JsonArray labelArray = jObject.getAsJsonArray("labels");
                /*for (JsonElement labelElement : labelArray) {
                    JsonObject lObject = labelElement.getAsJsonObject();
                    int label = lObject.get("label").getAsInt();
                    int level = lObject.get("level").getAsInt();
                    JsonObject detailsObject=lObject.getAsJsonObject("details");
                    JsonArray hintArray=detailsObject.getAsJsonArray("hint");
                }*/
                if (action == 0) {
                    System.out.println(String.format("taskId=%s,callback=%s,文本人工复审结果:通过", taskId, callback));
                } else if (action == 2) {
                    System.out.println(String.format("taskId=%s,callback=%s,文本人工复审结果:不通过,分类信息如下:%s", taskId, callback,
                                                     labelArray.toString()));
                }
            }
        } else {
            System.out.println(String.format("ERROR: code=%s, msg=%s", code, msg));
        }

    }
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""易盾内容安全文本离线检测结果获取接口python示例代码
接口文档: http://dun.163.com/api.html
python版本:python2.7
运行:
    1. 修改 SECRET_ID,SECRET_KEY,BUSINESS_ID 为对应申请到的值
    2. $ python text_check_callback_demo.py
"""
__author__ = 'yidun-dev'
__date__ = '2016/3/10'
__version__ = '0.1-dev'

import hashlib
import time
import random
import urllib
import urllib2
import json

class TextCheckCallbackAPIDemo(object):
    """文本离线检测结果获取接口示例代码"""
    API_URL = "https://as.dun.163yun.com/v3/text/callback/results"
    VERSION = "v3.1"

    def __init__(self, secret_id, secret_key, business_id):
        """
        Args:
            secret_id (str) 产品密钥ID,产品标识
            secret_key (str) 产品私有密钥,服务端生成签名信息使用
            business_id (str) 业务ID,云安全(易盾)根据产品业务特点分配
        """
        self.secret_id = secret_id
        self.secret_key = secret_key
        self.business_id = business_id

    def gen_signature(self, params=None):
        """生成签名信息
        Args:
            params (object) 请求参数
        Returns:
            参数签名md5值
        """
        buff = ""
        for k in sorted(params.keys()):
            buff += str(k)+ str(params[k])
        buff += self.secret_key
        return hashlib.md5(buff).hexdigest()

    def check(self):
        """请求易盾接口
        Returns:
            请求结果,json格式
        """
        params = {}
        params["secretId"] = self.secret_id
        params["businessId"] = self.business_id
        params["version"] = self.VERSION
        params["timestamp"] = int(time.time() * 1000)
        params["nonce"] = int(random.random()*100000000)
        params["signature"] = self.gen_signature(params)

        try:
            params = urllib.urlencode(params)
            request = urllib2.Request(self.API_URL, params)
            content = urllib2.urlopen(request, timeout=10).read()
            return json.loads(content)
        except Exception, ex:
            print "调用API接口失败:", str(ex)

if __name__ == "__main__":

    """示例代码入口"""
    SECRET_ID = "your_secret_id" # 产品密钥ID,产品标识
    SECRET_KEY = "your_secret_key" # 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露
    BUSINESS_ID = "your_business_id" # 业务ID,易盾根据产品业务特点分配
    text_check_callback_api = TextCheckCallbackAPIDemo(SECRET_ID, SECRET_KEY, BUSINESS_ID)

    ret = text_check_callback_api.check()
    if ret["code"] == 200:
        if len(ret["result"])==0:
            print "暂时没有人工复审结果需要获取,请稍后重试!"
        else:
            for result in ret["result"]:
                taskId = result["taskId"]
                callback=result["callback"]
                labelArray=json.dumps(result["labels"],ensure_ascii=False)
                if result["action"]==0:
                    print "taskId=%s,callback=%s,文本人工复审结果:通过" %(taskId,callback)
                else:
                    print "taskId=%s,callback=%s,文本人工复审结果:不通过,分类信息如下:%s" %(taskId,callback,labelArray)
    else:
        print "ERROR: code=%s, msg=%s" % (ret["code"], ret["msg"])
<?php
/** 产品密钥ID,产品标识 */
define("SECRETID", "your_secret_id");
/** 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露 */
define("SECRETKEY", "your_secret_key");
/** 业务ID,易盾根据产品业务特点分配 */
define("BUSINESSID", "your_business_id");
/**易盾内容安全服务文本离线检测结果获取接口地址 */
define("API_URL", "https://as.dun.163yun.com/v3/text/callback/results");
/** api version */
define("VERSION", "v3.1");
/** API timeout*/
define("API_TIMEOUT", 10);
/** php内部使用的字符串编码 */
define("INTERNAL_STRING_CHARSET", "auto");

/**
 * 计算参数签名
 * $params 请求参数
 * $secretKey secretKey
 */
function gen_signature($secretKey, $params){
    ksort($params);
    $buff="";
    foreach($params as $key=>$value){
        if($value !== null) {
           $buff .=$key;
           $buff .=$value;
        }
    }
    $buff .= $secretKey;
    return md5($buff);
}

/**
 * 将输入数据的编码统一转换成utf8
 * @params 输入的参数
 */
function toUtf8($params){
    $utf8s = array();
    foreach ($params as $key => $value) {
        $utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", INTERNAL_STRING_CHARSET) : $value;
    }
    return $utf8s;
}

/**
 * 内容安全请求接口简单封装
 * $params 请求参数
 */
function check(){
    $params = array();
    $params["secretId"] = SECRETID;
    $params["businessId"] = BUSINESSID;
    $params["version"] = VERSION;
    $params["timestamp"] = sprintf("%d", round(microtime(true)*1000));// time in milliseconds
    $params["nonce"] = sprintf("%d", rand()); // random int

    $params = toUtf8($params);
    $params["signature"] = gen_signature(SECRETKEY, $params);
    // var_dump($params);

    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'timeout' => API_TIMEOUT, // read timeout in seconds
            'content' => http_build_query($params),
        ),
    );
    var_dump($params);
    $context  = stream_context_create($options);
    $result = file_get_contents(API_URL, false, $context);
    if($result === FALSE){
        return array("code"=>500, "msg"=>"file_get_contents failed.");
    }else{
        return json_decode($result, true);
    }
}

// 简单测试
function main(){
    echo "mb_internal_encoding=".mb_internal_encoding()."\n";
    $ret = check();
    var_dump($ret);

    if ($ret["code"] == 200) {
        $result = $ret["result"];
         if(empty($result)){
            echo "暂时没有文本人工复审结果需要获取,请稍后重试!";
        }
        foreach($result as $index => $value){
            $action = $value["action"];
            $taskId = $value["taskId"];
            $callback = $value["callback"];
            $labelArray = $value["labels"];
            if ($action == 0) {
            echo "taskId={$taskId},callback={$callback},文本人工复审结果:通过\n";
            } else if ($action == 2) {
            echo "taskId={$taskId},callback={$callback},文本人工复审结果:不通过,分类信息如下:".json_encode($labelArray)."\n";
                }
        }
    }else{
        var_dump($ret);
    }
}

main();
?>
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;

namespace Com.Netease.Is.Antispam.Demo
{
    class TextCallbackDemo
    {

        public static void textCallBack()
        {
            /** 产品密钥ID,产品标识 */
            String secretId = "your_secret_id";
            /** 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露 */
            String secretKey = "your_secret_key";
            /** 业务ID,易盾根据产品业务特点分配 */
            String businessId = "your_business_id";
            /** 易盾内容安全服务文本离线检测结果获取接口地址 */
            String apiUrl = "https://as.dun.163yun.com/v3/text/callback/results";
            Dictionary<String, String> parameters = new Dictionary<String, String>();

            long curr = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            String time = curr.ToString();

            // 1.设置公共参数
            parameters.Add("secretId", secretId);
            parameters.Add("businessId", businessId);
            parameters.Add("version", "v3");
            parameters.Add("timestamp", time);
            parameters.Add("nonce", new Random().Next().ToString());

            // 2.生成签名信息
            String signature = Utils.genSignature(secretKey, parameters);
            parameters.Add("signature", signature);

            // 3.发送HTTP请求
            HttpClient client = Utils.makeHttpClient();
            String result = Utils.doPost(client, apiUrl, parameters, 10000);
            if(result != null)
            {
                JObject ret = JObject.Parse(result);
                int code = ret.GetValue("code").ToObject<Int32>();
                String msg = ret.GetValue("msg").ToObject<String>();
                if (code == 200)
                {
                    JArray array = (JArray)ret.SelectToken("result");
                    if (array==null || !array.HasValues)
                    {
                        Console.WriteLine("暂时没有文本人工复审结果需要获取,请稍后重试!");
                    }

                    foreach (var item in array)
                    {
                        JObject tmp = (JObject)item;
                        int action = tmp.GetValue("action").ToObject<Int32>();
                        String taskId = tmp["taskId"].ToObject<String>();
                        String callback = tmp.GetValue("callback").ToObject<String>();
                        JArray labelArray = (JArray)tmp.SelectToken("labels");
                        if (action == 0)
                        {
                             Console.WriteLine(String.Format("taskId={0},callback={1},文本人工复审结果:通过", taskId,callback));
                        }
                        else if (action == 2)
                        {
                             Console.WriteLine(String.Format("taskId={0},callback={1},文本人工复审结果:不通过,分类信息如下:{2}", taskId,callback,labelArray));
                        }
                    }
                }
                else
                {
                    Console.WriteLine(String.Format("ERROR: code={0}, msg={1}", code, msg));
                }
            }
            else
            {
                Console.WriteLine("Request failed!");
            }
        }
}
}
var utils=require("./utils");
//产品密钥ID,产品标识
var secretId="your_secret_id";
// 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露
var secretKey="your_secret_key";
// 业务ID,易盾根据产品业务特点分配
var businessId="your_business_id";
// 易盾内容安全服务文本检测结果获取接口地址
var apiurl="https://as.dun.163yun.com/v3/text/callback/results";
//请求参数
var post_data = {
    // 1.设置公有有参数
    secretId:secretId,
    businessId:businessId,
    version:"v3",
    timestamp:new Date().getTime(),
    nonce:utils.noncer()
};
var signature=utils.genSignature(secretKey,post_data);
post_data.signature=signature;
//http请求结果
var responseCallback=function(responseData){
    var data = JSON.parse(responseData);
    var code=data.code;
    var msg=data.msg;
    if(code==200){
        var result=data.result;
        if(result.length==0){
            console.log("暂时没有人工复审结果需要获取,请稍后重试!");
        }else{
            for(var i=0;i<result.length;i++){
                var obj=result[i];
                var action=obj.action;
                var taskId=obj.taskId;
                var callback=obj.callback;
                var labels=obj.labels;
                if(action==0){// 内容确认没问题,通过
                    console.log("taskId="+taskId+",callback="+callback+",文本人工复审结果:通过")
                }else if(action==2){// 内容非法,不通过,需删除
                    console.log("taskId="+taskId+",callback="+callback+",文本人工复审结果:不通过,分类信息如下:"+JSON.stringify(labels))
                }
            }
        }
    }else{
         console.log('ERROR:code=' + code+',msg='+msg);
    }
}
utils.sendHttpRequest(apiurl,"POST",post_data,responseCallback);

响应示例

当获取到离线结果时,输出示例如下:

{
    "code": 200,
    "msg": "ok",
    "result": [
        {
            "action": 2,
            "taskId": "a9840b389d2e483d9349cd62e9cda250",
            "callback": "ebfcad1c-dba1-490c-b4de-e784c2691768",
            "labels": [
                {
                    "label": 600,
                    "level": 2,
                    "details": {
                        "hint": [
                            "xxx"
                        ]
                    }
                }
            ]
        },
        {
            "action": 0,
            "taskId": "11140b389d2e483d9349cd62e9cdas11",
            "callback": "asdffcad1c-dba1-490c-b4de-e784c269112",
            "labels": [
                
            ]
        },
        
    ]
}

当无最新离线结果需要获取时,输出示例如下:

{
    "code": 200,
    "msg": "ok",
    "result": [
        
    ]
}
95163223