我是C ++初学者并使用Google任务API。
如何编写接受单词的C ++程序,然后调用Google Translate将其从英语翻译成法语,然后将生成的页面保存到本地文件?
例如,如果用户输入“river”,程序应调用Google Translate翻译成法语,结果页面为: http://translate.google.com/#en|fr|River%0A 该页面应该保存。
我完全阅读了官方文档:http://code.google.com/apis/language/translate/v2/getting_started.html 但我无法理解如何使用REST,而且我不熟悉JSON或AJAX。
答案 0 :(得分:0)
有人建议我使用 libcurl ,我会尝试看看。
答案 1 :(得分:0)
您需要某种HTTP库。我是Adrian所说的第二大部分,但是这里有一些(不完整的)Qt代码可以给你一个想法。
namespace {
const QString API_KEY = /* TODO */;
}
MyQObject :: MyQbject ()
: m_manager (new QNetworkAccessManager (this))
{
connect(manager, SIGNAL (finished (QNetworkReply *)),
this, SLOT (reply_finished (QNetworkReply *)));
}
void MyQObject :: fetch_translation (
QString words,
void (*on_receive)(const QString &))
{
// Let's assume asynchronous but non-concurrent requests.
m_on_receive = on_receive;
QString request =
"https://www.googleapis.com/language/translate/v2"
"?key=%1&source=en&target=de&q=%2";
// May want to url-encode 'words' first.
m_manager -> get (QUrl (request .arg (API_KEY) .arg (words));
}
void MyQObject :: reply_finished (QNetworkReply * reply)
{
m_on_receive (reply -> readAll ());
}
// ...
{
my_q_object -> translate ("hello, world", [](const QString & s) {
qWarning () << "translation is: " << s;
});
}
答案 2 :(得分:0)
我在某处看到了这些代码,但我不记得在哪里,无论如何都试试这个:
QString YourClass::translate(QString keyword, QString from, QString to)
{
//Translate URL
QString url = QString("http://translate.google.com/translate_a/t?client=t&text=%0&hl=%1&sl=%2&tl=%1&multires=1&prev=enter&oc=2&ssel=0&tsel=0&uptl=%1&sc=1").arg(keyword).arg(to).arg(from);
QNetworkAccessManager manager;
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
//Get reply from Google
do {
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
} while(!reply->isFinished());
//Convert to string
QString translation(reply->readAll());
reply->close();
//Free memory
delete reply;
//Remove [[[" from the beginning
translation = translation.replace("[[[\"", "");
//Extract final translated string
translation = translation.mid(0, translation.indexOf(",\"") - 1);
return translation;
}