如何使用必应翻译API?

15
我想使用Bing翻译API,但我很困惑。似乎有许多可能性(旧的和新的),但我不明白该做什么。
有人可以帮助我吗?
我想发送一个HTTP请求,如http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=<AppId>&to=de&text=World,并获取翻译。哪里可以获取AppId?
到目前为止,我已经完成了以下工作:
  1. 签署了免费API使用协议(https://datamarket.azure.com/dataset/bing/microsofttranslator
  2. 创建了一个应用程序:https://datamarket.azure.com/developer/applications
现在我有Client_ID和Client_Secret,也有一个账户密钥(在此处可见:https://datamarket.azure.com/account
现在该怎么办?
非常感谢任何帮助!
3个回答

5

https://datamarket.azure.com 和 http://msdn.microsoft.com/en-us/library/dd576287.aspx 似乎已经无法使用了。 - Loran

4

请在http://api.microsofttranslator.com上查找链接。该API会在appid参数中获取访问令牌。请参阅文档中的“获取访问令牌”部分,了解如何获取该令牌。


我已经仔细阅读了所有内容,但是我还没有找到解决方案...也许我忽略了某些东西。此外,如果我正确理解access_token,你需要每隔x分钟创建它。我想要一个简单的静态appId,可以将其硬编码到我的应用程序中 ;) - Ph3n1x

2

如果您使用的是php,请随意使用以下说明:

定义您的密钥

$apis['azure']['id'] = 123456789
$apis['azure']['key'] = 'abcde123456';

类和函数

class AccessTokenAuthentication {
    function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
        try {
            $ch = curl_init();
            $paramArr = array (
                'grant_type'    => $grantType,
                'scope'         => $scopeUrl,
                'client_id'     => $clientID,
                'client_secret' => $clientSecret
            );
            $paramArr = http_build_query($paramArr);
            curl_setopt($ch, CURLOPT_URL, $authUrl);
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $strResponse = curl_exec($ch);
            $curlErrno = curl_errno($ch);
            if($curlErrno){
                $curlError = curl_error($ch);
                throw new Exception($curlError);
            }
            curl_close($ch);
            $objResponse = json_decode($strResponse);
            if($objResponse->error){
                throw new Exception($objResponse->error_description);
            }
            return $objResponse->access_token;
        } catch (Exception $e) {
            echo "Exception-".$e->getMessage();
        }
    }
}
class HTTPTranslator {
    function curlRequest($url, $authHeader, $postData=''){
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
        if($postData) {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
        $curlResponse = curl_exec($ch);
        $curlErrno = curl_errno($ch);
        if ($curlErrno) {
            $curlError = curl_error($ch);
            throw new Exception($curlError);
        }
        curl_close($ch);
        return $curlResponse;
    }
    function xmlLanguageCodes($languageCodes) {
        $requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
        if(sizeof($languageCodes) > 0){
            foreach($languageCodes as $codes) {
                $requestXml .= "<string>$codes</string>";
            }
        } else {
            throw new Exception('$languageCodes array is empty.');
        }
        $requestXml .= '</ArrayOfstring>';
        return $requestXml;
    }

    function xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr) {
        $requestXml = "<TranslateArrayRequest>".
        "<AppId/>".
        "<From>$fromLanguage</From>". 
        "<Options>" .
            "<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
            "<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$contentType</ContentType>" .
            "<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
            "<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
            "<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
            "<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
        "</Options>" .
        "<Texts>";
            foreach ($inputStrArr as $inputStr) {
                $requestXml .= "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">$inputStr</string>";
            }
        $requestXml .= "</Texts>".
        "<To>$toLanguage</To>" .
        "</TranslateArrayRequest>";
        return $requestXml;
    }
}

function get_language_names($locale="en") {
    global $list, $apis;
    try {
        $clientID = $apis['azure']['id'];
        $clientSecret = $apis['azure']['key'];
        $authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
        $scopeUrl = "http://api.microsofttranslator.com";
        $grantType = "client_credentials";
        $authObj = new AccessTokenAuthentication();
        $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
        $authHeader = "Authorization: Bearer ". $accessToken;
        foreach($list['translate'] as $k=>$iso) {
            $languageCodes[] = $k;
        }
        $url = "http://api.microsofttranslator.com/V2/Http.svc/GetLanguageNames?locale=$locale";
        $translatorObj = new HTTPTranslator();
        $requestXml = $translatorObj->xmlLanguageCodes($languageCodes);
        $curlResponse =$translatorObj->curlRequest($url, $authHeader, $requestXml);
        $xmlObj = simplexml_load_string($curlResponse);
        $i=0;
        foreach($xmlObj->string as $language) {
            $result[$languageCodes[$i]] = (string)$language;
            $i++;
        }
        return $result;
    } catch (Exception $e) {
        echo "Exception: " . $e->getMessage() . PHP_EOL;
    }
}

function get_translate($array, $from, $to, $html=false) {
    global $apis;
    try {
        $clientID = $apis['azure']['id'];
        $clientSecret = $apis['azure']['key'];
        $authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
        $scopeUrl = "http://api.microsofttranslator.com";
        $grantType = "client_credentials";
        $authObj = new AccessTokenAuthentication();
        $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
        $authHeader = "Authorization: Bearer ". $accessToken;

        $fromLanguage = $from;
        $toLanguage = $to;
        $inputStrArr = array_values($array);
        if($html) {
            $contentType = 'text/html';
            foreach($inputStrArr as $k=>$item) {
                $inputStrArr[$k] = htmlentities($inputStrArr[$k]);
            }
        } else {
            $contentType = 'text/plain';
        }

        $translatorObj = new HTTPTranslator();
        $requestXml = $translatorObj->xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr);
        $translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
        $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader, $requestXml);

        $xmlObj = simplexml_load_string($curlResponse);
        foreach($xmlObj->TranslateArrayResponse as $translatedArrObj){
            $result[] = (string)$translatedArrObj->TranslatedText;
        }
        return $result;
    } catch (Exception $e) {
        echo "Exception: " . $e->getMessage() . PHP_EOL;
    }
}

function get_translate_single($input, $from, $to, $html=false) {
    global $apis;
    try {
        $clientID = $apis['azure']['id'];
        $clientSecret = $apis['azure']['key'];
        $authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
        $scopeUrl = "http://api.microsofttranslator.com";
        $grantType = "client_credentials";
        $authObj = new AccessTokenAuthentication();
        $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
        $authHeader = "Authorization: Bearer ". $accessToken;

        $fromLanguage = $from;
        $toLanguage = $to;
        if($html) {
            $contentType = 'text/html';
            $input = htmlentities($input);
        } else {
            $contentType = 'text/plain';
        }

        # params
        $params = "text=".urlencode($input)."&to=".$toLanguage."&from=".$fromLanguage;
        $translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?".$params;

        # object
        $translatorObj = new HTTPTranslator();
        $curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);

        # interprets a string of XML into an object.
        $xmlObj = simplexml_load_string($curlResponse);
        foreach((array)$xmlObj[0] as $val){
            $result = $val;
        }
        return $result;
    } catch (Exception $e) {
        echo "Exception: " . $e->getMessage() . PHP_EOL;
    }
}

这些调用

echo get_translate_single('horse', 'en', 'es'); //this will print 'caballo'

或者

echo get_translate(array('horse', 'house'), 'en', 'es'); //this will print array('caballo', 'casa')

就是这样,玩得开心,记得遵守服务条款


哇,谢谢。这个可以用啊兄弟。但是我遇到了这个错误 注意:未定义的属性:stdClass :: $ error in {someplace} - Rohman HM
@HabibRohman 请尝试降低您的显示错误级别:display_errors(false); error_reporting(0); - Andres SK
@FlashThunder 我同意,但那只是一个快速(且暂时的)修复开发环境的方法。 - Andres SK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接