帮助与文档 > 产品文档 > 拍照搜题 > API 文档

简介

Hi,您好,欢迎使用有道智云拍照搜题服务。

本文档主要针对需要集成拍照搜题 服务HTTP API的开发工程师,详细描述有道智云拍照搜题能力及如何集成的技术内容。

如果您是非技术人员,想要体验我们的产品能力,请点击拍照搜题体验中心。也可以下拉到网站底部,扫描小程序二维码进行体验。

如果您对文档内容有任何疑问,可以通过以下几种方式联系我们:

客服QQ:1906538062

官方交流群:685832941

联系邮箱:zyservice@corp.youdao.com

接口介绍

接口地址:

http接口: http://openapi.youdao.com/ocrquestionapi

https接口: https://openapi.youdao.com/ocrquestionapi

接口参数:
调用API需要向接口发送以下字段来访问服务。

字段名类型含义必填备注
qtext要请求的的图片文件的base64编码字符串true必须是Base64编码
appKeytext应用 IDtrue可在 应用管理 查看
salttext随机数true
curtimetext当前时间戳true
signtext签名,通过sha256(appKey+input+salt+curtime+密钥)生成;input的生成规则见表下的备注true
signTypetext签名类型truev2
typetext上传类型, 仅支持base64上传,请填写固定值1true1

input=q字符串的前10个字符 + q字符串长度 + q字符串后十个字符(当q长度大于20)或 q字符串(当q长度小于等于20).

具体示例如下:
a.比如:q="Welcome to youdao AICloud.",字符串长度为26,大于20,其input="Welcome to"(前10个字符) + 26(字符串长度) + "o AICloud."(q字符串后10个字符)。
b.比如:q = "sdT4bWrjS",字符串长度为9,小于20,input = "sdT4bWrjS".

输出结果

输出字段介绍

响应结果是以json形式输出,包含字段如下表所示:

字段含义
errorCode识别结果错误码,一定存在
data数据
-text图片题目OCR结果
-questions相关题目
--id答案
--content题目内容
--answer答案
--analysis解析
--knowledge知识点

输出结果示例

{
    "data": {
        "questions": [{
            "answer": "<p>CM=DM </p><p><br/></p>",
            "id": "894fd7be65ce7b0288188bd871eebd08",
            "analysis": "<p>因为OP平分∠AOB, PC⊥OA于点C, PD⊥OB于点D,所以PD=PC,∠DPM=∠CPM.又因为PM=<br/>PM,所以△MPD≌△MPC,所以CM=DM. </p>",
            "content": "<p>如图,OP平分∠AOB, PC⊥OA于点C, PD⊥OB于点D,M为OP上任意一点,连接CM, DM,则CM和DM的大小关系是______.<br/></p><p><img src=\"http://nos.netease.com/yd-searchq/17eb37cb-1990-4453-aea8-ca151ae066fe.png\" title=\"1533365392716.png\" alt=\"blob.png\"/></p>",
            "knowledge": ""
        }, {
            "answer": "相等",
            "id": "fe9ee50505cdbd32244be8ba4cd20e2c",
            "analysis": "∵OP平分∠AOB&#xff0c;PC⊥OA&#xff0c;PD⊥OB&#xff0c; <br />∴PC&#61;PD&#xff0c;∠OPC&#61;∠OPD&#xff0c; <br />在△CPM和△DPM中&#xff0c;<img src=\"http://nos.netease.com/yd-searchq/c502f498-05e3-4828-8286-feb1a3d21abc.gif\" />&#xff0c; <br />∴△CPM≌△DPM(SAS)&#xff0c; <br />∴CM&#61;DM&#xff0e; <br />故答案为&#xff1a;相等&#xff0e; <br />根据角平分线上的点到角的两边距离相等可得PC&#61;PD&#xff0c;再求出∠OPC&#61;∠OPD&#xff0c;然后利用“边角边”证明△CPM和△DPM全等&#xff0c;根据全等三角形对应边相等可得CM&#61;DM&#xff0e; <br />本题考查了角平分线上的点到角的两边距离相等的性质&#xff0c;全等三角形的判定与性质&#xff0c;熟记性质并确定出全等三角形是解题的关键&#xff0e;",
            "content": "<img src=\"http://nos.netease.com/yd-searchq/a102f7ea-9c15-4a1d-afde-64f9d226ba57.gif\" />如图&#xff0c;OP平分∠AOB&#xff0c;PC⊥OA于C&#xff0c;PD⊥OB于D&#xff0e;M为OP上任意一点&#xff0c;连结CM、DM&#xff0c;则CM和DM的大小关系是 ______ &#xff0e;",
            "knowledge": "图形的性质>>图形认识初步>>角平分线的性质"
        }, {
            "answer": "解&#xff1a;∵OP平分∠AOB&#xff0c;PC⊥OA&#xff0c;PD⊥OB&#xff0c;<br />∴PC&#61;PD&#xff0c;∠OPC&#61;∠OPD&#xff0c;<br />在△CPM和△DPM中&#xff0c; \\( \\left\\{\\begin{array}{c}CP&#61;DP\\\\∠OPC&#61;∠OPD\\\\PM&#61;PM\\end{array}\\right. \\) &#xff0c;<br />∴△CPM≌△DPM(SAS)&#xff0c;<br />∴CM&#61;DM&#xff0e;<br />故答案为&#xff1a;相等&#xff0e;",
            "id": "d2db5fecc55c78092298f0889482dd44",
            "analysis": "本题考查了角平分线上的点到角的两边距离相等的性质&#xff0c;全等三角形的判定与性质&#xff0c;熟记性质并确定出全等三角形是解题的关键&#xff0e;",
            "content": "<img src=\"http://nos.netease.com/yd-searchq/8b8c0270-8fa5-4791-be64-fcf4652033e7.jpg\" /> <br />如图&#xff0c;OP平分∠AOB&#xff0c;PC⊥OA于C&#xff0c;PD⊥OB于D&#xff0e;M为OP上任意一点&#xff0c;连结CM、DM&#xff0c;则CM和DM的大小关系是__&#xff0e;",
            "knowledge": "角平分线的性质,全等三角形的判定与性质"
        }],
        "text": "如-3-11,0 , 平分∠AOB,PC OA于C.PDLO1S于D,M为OP上H 意一点,连接CM,DM,则CM和DM的大小关系是 ,"
    },
    "errorCode": "0"
}

支持的图片

目前支持英文的语音评测。

格式支持:jpg/png/bmp

尺寸限制:1MB以下

错误代码列表

错误码含义
101缺少必填的参数
102不支持的语言类型
103请求文本过长
104不支持的API类型
105不支持的签名类型
106不支持的响应类型
107不支持的传输加密类型
108appKey无效
109batchLog格式不正确
110无相关服务的有效实例
111用户无效
112请求服务无效
113请求文本不能为空
201解密失败
202签名检验失败
203访问IP地址不在可访问IP列表
301词典查询失败
302小语种翻译失败
303服务的异常
401账户已经欠费停止
402offlinesdk不可用
411访问频率受限,请稍后访问
412超过最大请求字符数
12001图片尺寸过大
12002图片base64解密失败
12003引擎服务器返回错误
12004图片为空
12005不支持的识别图片类型
12006图片无匹配结果

常用语言 Demo

Java 示例
Python 示例
C# 示例
PHP 示例
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class OcrquestionV1Demo {

    private static Logger logger = LoggerFactory.getLogger(OcrquestionV1Demo.class);

    private static final String YOUDAO_URL = "https://openapi.youdao.com/ocrquestionapi";

    private static final String APP_KEY = "您的应用ID";

    private static final String APP_SECRET = "您的应用密钥";

    public static void main(String[] args) throws IOException {

        Map<String,String> params = new HashMap<String,String>();
        String q = loadAsBase64("图片的路径");
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("q", q);
        params.put("signType", "v2");
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        params.put("curtime", curtime);
        String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);
        params.put("appKey", APP_KEY);
        params.put("salt", salt);
        params.put("sign", sign);
        String result = requestForHttp(YOUDAO_URL,params);
        /** 处理结果 */
        System.out.println(result);
    }

    public static String requestForHttp(String url,Map<String,String> params) throws IOException {
        String result = "";

        /** 创建HttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /** httpPost */
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String,String>> it = params.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,String> en = it.next();
            String key = en.getKey();
            String value = en.getValue();
            paramsList.add(new BasicNameValuePair(key,value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(paramsList,"UTF-8"));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try{
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity,"UTF-8");
            EntityUtils.consume(httpEntity);
        }finally {
            try{
                if(httpResponse!=null){
                    httpResponse.close();
                }
            }catch(IOException e){
                logger.info("## release resouce error ##" + e);
            }
        }
        return result;
    }

    /**
     * 生成加密字段
     */
    public static String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes();
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String loadAsBase64(String imgFile)
  {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理

    File file = new File(imgFile);
    if(!file.exists()){
        logger.error("文件不存在");
        return null;
    }
    InputStream in = null;
    byte[] data = null;
      //读取图片字节数组
    try
    {
        in = new FileInputStream(imgFile);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
      //对字节数组Base64编码
    return Base64.getEncoder().encodeToString(data);//返回Base64编码过的字节数组字符串
  }

  public static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        String result;
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }
}
# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import base64
import hashlib
import time

reload(sys)
sys.setdefaultencoding('utf-8')

YOUDAO_URL = 'https://openapi.youdao.com/ocrquestionapi'
APP_KEY = '您的应用ID'
APP_SECRET = '您的应用密钥'


def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()


def do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)


def connect():
    f = open(r'图片的路径', 'rb')  # 二进制方式打开图文件
    q = base64.b64encode(f.read())  # 读取文件内容,转换为base64编码
    f.close()

    data = {}
    data['q'] = q
    data['signType'] = 'v2'
    curtime = str(int(time.time()))
    data['curtime'] = curtime
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)
    data['appKey'] = APP_KEY
    data['salt'] = salt
    data['sign'] = sign

    response = do_request(data)
    print response.content


if __name__ == '__main__':
    connect()
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace zhiyun_csharp_demo
{
    class OcrquestionV1Demo
    {
        public static void Main()
        {
            Dictionary<String, String> dic = new Dictionary<String, String>();
            string url = "https://openapi.youdao.com/ocrquestionapi";
            string q = LoadAsBase64("图片的路径");
            string appKey = "您的应用ID";
            string appSecret = "您的应用密钥";
            string salt = DateTime.Now.Millisecond.ToString();
            dic.Add("q", System.Web.HttpUtility.UrlEncode(q));
            dic.Add("signType", "v2");
            TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
            long millis = (long) ts.TotalMilliseconds;
            string curtime = Convert.ToString(millis / 1000);
            dic.Add("curtime", curtime);
            string signStr = appKey + Truncate(q) + salt + curtime + appSecret;;
            string sign = ComputeHash(signStr, new SHA256CryptoServiceProvider());
            dic.Add("appKey", appKey);
            dic.Add("salt", salt);
            dic.Add("sign", sign);
            string result = Post(url, dic);
            Console.WriteLine(result);
        }

        protected static string ComputeHash(string input, HashAlgorithm algorithm)
        {
          Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
          Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
          return BitConverter.ToString(hashedBytes).Replace("-", "");
        }

        protected static string Truncate(string q)
        {
            if (q == null)
            {
               return null;
            }
            int len = q.Length;
            return len <= 20 ? q : (q.Substring(0, 10) + len + q.Substring(len - 10, 10));
        }

        protected static string LoadAsBase64(string filename)
        {
            try
            {
                FileStream filestream = new FileStream(filename, FileMode.Open);
                byte[] arr = new byte[filestream.Length];
                filestream.Position = 0;
                filestream.Read(arr, 0, (int)filestream.Length);
                filestream.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        protected static string Post(string url, Dictionary<String, String> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
    }
}
<?php
define("CURL_TIMEOUT",   2000);
define("URL",            "https://openapi.youdao.com/ocrquestionapi");
define("APP_KEY",        "您的应用ID"); // 替换为您的应用ID
define("SEC_KEY",        "您的应用密钥"); // 替换为您的密钥

function do_request($q)
{
                     $salt = create_guid();
                     $args = array(
        'appKey' => APP_KEY,
        'salt' => $salt,
    );
                     $args['q'] = $q;
                     $args['signType'] = 'v2';
                     $curtime = strtotime("now");
                     $args['curtime'] = $curtime;
                     $signStr = APP_KEY . truncate($q) . $salt . $curtime . SEC_KEY;
                     $args['sign'] = hash("sha256", $signStr);
                     $ret = call(URL, $args);
    print_r($ret);
                     $ret = json_decode($ret, true);
    return $ret;
}

// 发起网络请求
function call($url, $args=null, $method="post", $testflag = 0, $timeout = CURL_TIMEOUT, $headers=array())
{
                     $ret = false;
                     $i = 0;
    while($ret === false)
    {
        if($i > 1)
            break;
        if($i > 0)
        {
            sleep(1);
        }
                     $ret = callOnce($url, $args, $method, false, $timeout, $headers);
                     $i++;
    }
    return $ret;
}

function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = CURL_TIMEOUT, $headers=array())
{
                     $ch = curl_init();
    if($method == "post")
    {
                     $data = convert($args);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    else
    {
                     $data = convert($args);
        if($data)
        {
            if(stripos($url, "?") > 0)
            {
                     $url .= "&$data";
            }
            else
            {
                     $url .= "?$data";
            }
        }
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(!empty($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    if($withCookie)
    {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
    }
                     $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

function convert(&$args)
{
                     $data = '';
    if (is_array($args))
    {
        foreach ($args as $key=>$val)
        {
            if (is_array($val))
            {
                foreach ($val as $k=>$v)
                {
                     $data .= $key.'['.$k.']='.rawurlencode($v).'&';
                }
            }
            else
            {
                     $data .="$key=".rawurlencode($val)."&";
            }
        }
        return trim($data, "&");
    }
    return $args;
}

// uuid generator
function create_guid(){
                     $microTime = microtime();
    list($a_dec, $a_sec) = explode(" ", $microTime);
                     $dec_hex = dechex($a_dec* 1000000);
                     $sec_hex = dechex($a_sec);
    ensure_length($dec_hex, 5);
    ensure_length($sec_hex, 6);
                     $guid = "";
                     $guid .= $dec_hex;
                     $guid .= create_guid_section(3);
                     $guid .= '-';
                     $guid .= create_guid_section(4);
                     $guid .= '-';
                     $guid .= create_guid_section(4);
                     $guid .= '-';
                     $guid .= create_guid_section(4);
                     $guid .= '-';
                     $guid .= $sec_hex;
                     $guid .= create_guid_section(6);
    return $guid;
}

function truncate($q) {
                     $len = strlen($q);
    return $len <= 20 ? $q : (substr($q, 0, 10) . $len . substr($q, $len - 10, $len));
}

function ensure_length(&$string, $length){
                     $strlen = strlen($string);
    if($strlen < $length)
    {
                     $string = str_pad($string, $length, "0");
    }
    else if($strlen > $length)
    {
                     $string = substr($string, 0, $length);
    }
}

function create_guid_section($characters){
                     $return = "";
    for($i = 0; $i < $characters; $i++)
    {
                     $return .= dechex(mt_rand(0,15));
    }
    return $return;
}
// 输入
                     $file = "图片的路径";
                     $fp = fopen($file, "r") or die("Can't open file");
// base64编码
                     $q = base64_encode(fread($fp, filesize($file)));
fclose($fp);
do_request($q);
?>
文档是否有帮助解决问题?

如有其它疑问,可在此提交意见和反馈
详细描述(选填)
联系邮箱(选填)
留下您的合作信息,专业顾问将联系您提供免费的咨询
是否为渠道商:
服务类型:
详细分类:
所属地区:
所属行业:
公司名称:
业务简介:
使用场景:
使用量级:
联系人姓名:
联系人电话:
联系人邮箱:
联系人职务:
来源渠道:
verificatiton pics
验证码:
 
联系方式
合作咨询
联系电话:010-8255-8901
商务合作:
投诉反馈:
地       址:北京市海淀区西北旺东路10号院 中关村软件园二期西区7号 网易(北京)公司
微信公众号
微信小程序
 
 
©2019 网易公司 京ICP证080268号