HTTP接入文档
NxSun翻译API通过HTTP协议接口对外提供多语种互译服务。您只需要通过调用翻译API,传入待翻译的内容,并指定要翻译的源语言(支持源语言语种自动检测)和目标语言种类,就可以得到相应的翻译结果。
                翻译API HTTP地址:
                http://fanyi.nxsun.com/customer/api/translate
                只支持POST方法发送请求
            
| 字段名 | 类型 | 必填参数 | 描述 | 备注 | 
|---|---|---|---|---|
| q | text | Y | 请求翻译的内容 | UTF-8编码,单个词条或词条列表(数组)序列化 | 
| sn | String | Y | 身份唯一标识 | UTF-8编码 | 
| sl | String | Y | 翻译源语言 | 语言列表(可设置为auto) | 
| tl | String | Y | 翻译目标语言 | 语言列表 | 
| tt | String | Y | 时间戳,需要取整的字符串 | 时间戳是自1970年1月1日(00:00:00 GMT) 以来的秒数或毫秒数,它也被称为Unix时间戳 | 
| hk | String | Y | MD5(timestamp+API_KEY) | 在时间戳timestamp后拼接API_KEY,并对 拼接字符串计算MD5,MD5使用字符串格式 | 
| id | String | N | 帮助用户,难一标识每次请求 | 返回结果中会原样返回该字段值,可以省略 | 
注:q的值可以是一个词条,或者是多个词条的数据的序列化字符串。为了保证翻译质量和速度,单次请求的长度控制在1024字节以内
返回结果是json格式,包含以下字段:
| 字段名 | 类型 | 描述 | 
|---|---|---|
| status | INT | 0表示成功,-1表示失败 | 
| msg | String | 请求状态信息;success,error | 
| id | String | 用户请求传入的ID,原样返回,也可以为空 | 
| data | json | 是一个json结构体,里面包含相应的翻译结果 | 
| data.tl | String | 请求时的目标语言二字码 | 
| data.sl | String | 请求时的源语言二字码 | 
| data.tr | Array | 翻译结果,按请求时的词条顺序返回 | 
HTTP协议接口,增加或修改术语库
                http://fanyi.nxsun.com/customer/api/add/glossary
                只支持POST方法发送请求
            
| 字段名 | 类型 | 必填参数 | 描述 | 备注 | 
|---|---|---|---|---|
| sn | String | Y | 身份唯一标识 | UTF-8编码 | 
| sw | Text | Y | 源词条 | 术语源词条 | 
| sl | String | Y | 翻译源语言 | 语言列表(必须为二字吗) | 
| tw | Text | Y | 翻译结果 | 对于语言的翻译结果 | 
| tl | String | Y | 翻译目标语言 | 语言列表 | 
| tt | String | Y | 时间戳,需要取整的字符串 | 时间戳是自1970年1月1日(00:00:00 GMT) 以来的秒数或毫秒数,它也被称为Unix时间戳 | 
| hk | String | Y | MD5(timestamp+API_KEY) | 在时间戳timestamp后拼接API_KEY,并对 拼接字符串计算MD5,MD5使用字符串格式 | 
注:术语不要包含特殊字符,否则可能不能正确的应用到正式的翻译结果,尽可能是短词条或短句
返回结果是json格式,包含以下字段:
| 字段名 | 类型 | 描述 | 
|---|---|---|
| status | INT | 0表示成功,-1表示失败 | 
| msg | String | 请求状态信息;success,error | 
| status (int) | 备注 | 
|---|---|
| 1 | 请求成功,但是翻译失败 | 
| 0 | 请求成功,并且翻译成功 | 
| -1 | 发生未知错误,保留记录,联系NxSun | 
源语言语种不确定时可设置为 auto,目标语言语种不可设置为 auto。
| 语言二字码 | 名称 | 
|---|---|
| el | 希腊语 | 
| eo | 世界语 | 
| en | 英语 | 
| cn | 简体中文 | 
| af | 南非荷兰语 | 
| vi | 越南语 | 
| ca | 加泰罗尼亚语 | 
| it | 意大利语 | 
| iw | 希伯来语 | 
| cy | 威尔士语 | 
| ar | 阿拉伯语 | 
| ga | 爱尔兰语 | 
| cs | 捷克语 | 
| et | 爱沙尼亚语 | 
| gl | 加利西亚语 | 
| id | 印尼语 | 
| es | 西班牙语 | 
| ru | 俄语 | 
| nl | 荷兰语 | 
| pt | 葡萄牙语 | 
| no | 挪威语 | 
| tw | 繁体中文 | 
| tr | 土耳其语 | 
| lt | 立陶宛语 | 
| lv | 拉托维亚语 | 
| tl | 菲律宾语 | 
| th | 泰语 | 
| ro | 罗马尼亚语 | 
| is | 冰岛语 | 
| pl | 波兰语 | 
| yi | 意第绪语 | 
| be | 白俄罗斯语 | 
| fr | 法语 | 
| bg | 保加利亚语 | 
| uk | 乌克兰语 | 
| hr | 克罗地亚语 | 
| de | 德语 | 
| ht | 海地克里奥尔语 | 
| da | 丹麦语 | 
| fa | 波斯语 | 
| hi | 印地语 | 
| fi | 芬兰语 | 
| hu | 匈牙利语 | 
| ja | 日语 | 
| sr | 塞尔维亚语 | 
| sq | 阿尔巴尼亚语 | 
| kk | 哈萨克语 | 
| ko | 韩语 | 
| sv | 瑞典语 | 
| mk | 马其顿语 | 
| sk | 斯洛伐克语 | 
| mn | 蒙古语 | 
| mt | 马耳他语 | 
| ms | 马来语 | 
| sl | 斯洛文尼亚语 | 
| sw | 斯瓦希里语 | 
| my | 缅甸语 | 
| bn | 孟加拉语 | 
| ur | 乌尔都语 | 
Python 示例:
#coding=utf8
import json
import time
import requests
import hashlib
url = "http://fanyi.nxsun.com/customer/api/translate"
api_key = "xxxxxxxxxx"
def md5(data):
    m = hashlib.md5()
    m.update(data)
    return m.hexdigest()
def translate(wd, sl, tl):
    tt = str(int(time.time()*1000))
    data = {
        "q": wd,
        "sl": sl,
        "tl": tl,
        "sn": "service_name",
        "tt": tt,
        "hk": md5(tt + api_key)
    }
    res = requests.post(url, data)
    if res.status_code == 200:
        result = json.loads(res.text)
        if result["status"] == 0 and result["msg"] == "success":
            print result
        else:
            print result
            print "failure"
    else:
        print "failure"
translate(json.dumps(["This is a good book."]), "en", "ru")
                
            C# 示例:(根据具体情况调试)
    static public string GetMD5HashFromString(string str)
    {
        //需要将字符串转换成字节数组
        byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
        //创建MD5对象
        MD5 md5 = MD5.Create();
        //返回一个加密好的数组
        byte[] retVal = md5.ComputeHash(bytValue);
        string strNew = "";
        for (int i = 0; i < retVal.Length; i++)
        {
            strNew += retVal[i].ToString("x2");
        }
        return strNew;
    }
    public static string GetTimeStamp(DateTime dt)
    {
        TimeSpan ts = dt - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        String url = "http://fanyi.nxsun.com/customer/api/translate?";
        string api_key = "xxxxxxxxxx";
        DateTime now1 = DateTime.Now;
        string data = "sn=XXXXXX&sl=en&tl=cn&q='hello world'&tt=" + GetTimeStamp(now1) + "&hk=" +
                    GetMD5HashFromString(GetTimeStamp(now1) + api_key);
        url = url + data;
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.Method = "POST";
        httpWebRequest.BeginGetResponse(new AsyncCallback(RequestTranslateCallBack), httpWebRequest);
    }
                
            JAVA 示例:
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.lang.String;
import java.lang.StringBuffer;
import java.util.List;
import java.security.MessageDigest;
import java.util.ArrayList;
public class httpPostJson {
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
    "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private static String byteArrayToHexString(byte[] b){
        StringBuffer resultSb = new StringBuffer();
        for(int i = 0; i < b.length; i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }
    private static String byteToHexString(byte b){
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    public static String encodeByMd5(String originString){
        if (originString != null){
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] results = md.digest(originString.getBytes());
                String resultString = byteArrayToHexString(results);
                return resultString;
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return null;
    }
    public static String translate(String word) {
        try {
            String URL = "http://fanyi.nxsun.com/customer/api/translate";
            String sn = "xxxx";
            String sl = "en";
            String tl = "cn";
            String q = word;
            String api_key = "xxxxxxxxxx";
            String tt = String.valueOf(System.currentTimeMillis());
            String hk = encodeByMd5(tt + api_key);
            //设置请求参数
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("q", q));
            params.add(new BasicNameValuePair("sl", sl));
            params.add(new BasicNameValuePair("tl", tl));
            params.add(new BasicNameValuePair("sn", sn));
            params.add(new BasicNameValuePair("tt", tt));
            params.add(new BasicNameValuePair("hk", hk));
            //创建post请求
            HttpPost httppost = new HttpPost(URL);
            //添加参数
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            //设置编码
            HttpResponse response = new DefaultHttpClient().execute(httppost);
            //发送post,并返回一个HttpResponse对象
            if(response.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(response.getEntity());
                return result;
            }else{
                return null;
            }
        } catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args){
        //注意,这里的翻译词条,可以是一个单个词条,也可以是json序列化的一个数组
        //多个的时候,'["hello world", "this is a dog"]'
        //单个词翻译
        String word = "hello world";
        String ret = translate(word);
        System.out.println(ret);
        //多词同时翻译
        String words = '['+ "\"hello world\"" + "," + "\"this is dog\"" +']';
        String rets = translate(words);
        System.out.println(rets);
    }
}
                
            PHP 示例:
<?php
function translate($url, $sl, $tl, $sn, $api_key, $word) {
    $postUrl = $url;
    $tt = (string)mktime();
    $hk = md5($tt.$api_key);
    $curlPost = array(
        'method' => 'POST',
        'q' => $word,
        'sl' => $sl,
        'tl' => $tl,
        'sn' => $sn,
        'tt' => $tt,
        'hk' => $hk,
        'timeout' => 20 // 超时时间(单位:s)
    );
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}
                
        1.如果在一次请求中翻译多段文本?
将需要翻译的多段文本放在一个数组中,然后进行序列化成相应的字符串,提交翻译请求。
2.为什么返回总是授权失败?
首先,先检查你本机的时间是否正确。然后获取时间戳tt,需要取整的字符串。然后与分配的api_key字符串合并,计算MD5值为该次请求的hash_key值。
3.源语言是auto和指定语言有什么区别?
                1) 设置为auto后,翻译引擎首先会去进行语言检测,确定源语言后,进行翻译,
                这样就会比直接传入准确的源语言响应时间原理上来说会慢点,但是基本感受不出来;
                2) 源语言的检测,也有精度问题,特短词条,特别是拉丁语系中,
                多种语言都会出现的单词,会有检测错误的几率;
                3) 请求auto,返回会是检测出来的源语言二字码。
            
3.对于自有专业术语库,能否应用到翻译中?
我们支持建立属于自己的专业术语库,并且翻译中会优先采用术语库中的翻译。术语库的建立,可以联系NxSun获取API接口。
4.什么收费模式?
我们统计请求的翻译请求接受到需要翻译的字符数(包括字符串中可能的格式字符数),按字符数收费。
5.一次请求中,翻译的词支持什么格式?
                1)每次请求,都可以翻译多个词条,这些词条需要保存在数组中,然后对这个数组进行序列化。例如:'["hello world", "This is a book"]';
                2)对于单个词条,支持格式:文本字符串、xml片段、html片段,json片段。