Qt:使用百度翻译API,做全平台的翻译工具

百度翻译文档:

http://developer.baidu.com/wiki/index.php?title=帮助文档首页/百度翻译/翻译API


使用百度翻译的API,需要申请一个ApiKey才可以正常使用。

申请的方法在上方文档中都有说明。


ps:我的示例里面有放了一个可用的ApiKey,但是仅供各位测试使用,有需要开发App的请自行申请,放在示例中的Key我可能随时会撤销。

ps:编译需要开启C++11的支持


核心代码:

JasonQt_Translation.h

#ifndef __JasonQt_Translation_h__
#define __JasonQt_Translation_h__

// Qt lib import
#include 
#include 
#include 

// JasonQt lib import
#include "JasonQt_Net.h"

namespace JasonQt_Translation
{

class BaiduTranslation: public QObject
{
    Q_OBJECT

private:
    QString m_apiKey;

    JasonQt_Net::HTTP m_http;

public:
    BaiduTranslation(const QString &apiKey);

public slots:
    std::pair translation(const QString &string, const QString &from = "auto", const QString &to = "auto");
};

}

#endif//__JasonQt_Translation_h__


JasonQt_Translation.cpp

#include "JasonQt_Translation.h"

// BaiduTranslation
JasonQt_Translation::BaiduTranslation::BaiduTranslation(const QString &apiKey):
    m_apiKey(apiKey)
{ }

std::pair JasonQt_Translation::BaiduTranslation::translation(const QString &string, const QString &from, const QString &to)
{
    QNetworkRequest request(QUrl("http://openapi.baidu.com/public/2.0/bmt/translate"));
    const QString format("client_id=%1&q=%2&from=%3&to=%4");
    QByteArray buf;

    request.setRawHeader("Content-Type", "application");

    if(!m_http.post(request, format.arg(m_apiKey, string, from, to).toUtf8(), buf)) { return { false, QString() }; }

    QJsonObject data(QJsonDocument::fromJson(buf).object());

    if(!data.contains("trans_result")
     || data["trans_result"].toArray().isEmpty()
     || !data["trans_result"].toArray()[0].toObject().contains("dst")) { return { false, QString() }; }

    return { true, data["trans_result"].toArray()[0].toObject()["dst"].toString() };
}


效果:

Qt:使用百度翻译API,做全平台的翻译工具_第1张图片


示例下载地址:

https://github.com/188080501/BaiduTranslationDemo


你可能感兴趣的:(Qt)