Qt调用谷歌翻译API
作者:互联网
原理:模拟Google翻译网页请求。
ps:频繁调用会封IP哦
QString GoogleAPI::translateText(QString text, QString sourceLang, QString targetLang)
{
QString retStr="";
QString finalPath = m_path +"?client="+m_client+"&sl="+sourceLang+"&tl="+targetLang+"&dt=t&q="+ text.toUtf8().toPercentEncoding();
postHttp(finalPath, retStr);
return retStr;
}
int GoogleAPI::postHttp(QString finalPath, QString& p_translate)
{
QNetworkRequest request;
request.setUrl(QUrl::fromEncoded(finalPath.toUtf8()));
request.setHeader(QNetworkRequest::UserAgentHeader, m_userAgent);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
QTimer timer;
timer.setInterval(10000); // 设置超时时间 10 秒
timer.setSingleShot(true); // 单次触发
QNetworkAccessManager networkManager;
QNetworkReply *pReply = networkManager.get(request);
QEventLoop loop;
connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
connect(pReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
if (timer.isActive())
{
// 处理响应
timer.stop();
if (pReply->error() != QNetworkReply::NoError)
{
// 错误处理
qDebug()<<"GoogleAPI::postHttp() QNetworkReply Error String : " << pReply->errorString();
return -1;
}
else
{
QByteArray data = pReply->readAll();
//如果有错误的序列号
int errorIndex = data.indexOf("error_code");
if (errorIndex != -1)
return errorIndex;
//直接截取 QByteArray data
QString dstStr = QString(data);
int startPos = dstStr.indexOf("[\"");
int endPos = dstStr.indexOf("\",\"");
p_translate = dstStr.mid(startPos + 3, endPos - startPos - 3);
//用一个js类型变量获得返回值的内容 ----json解析太麻烦
// QJsonParseError jsonError;
// QJsonDocument doucment = QJsonDocument::fromJson(data, &jsonError);
// if(!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
// {
// if (doucment.isArray())
// {
// QJsonArray array = doucment.array();
// if(array.count() > 0)
// {
// QJsonValue value = array.at(0);
// if(value.isArray())
// {
// QJsonArray array1 = value.toArray();
// if(array1.count() > 0)
// {
// QJsonValue value1 = array1.at(0);
// if(value1.isArray())
// {
// QJsonArray array2 = value1.toArray();
// if(array2.count() > 0)
// {
// QString s = array2.at(0).toString();
// qDebug()<< s;
// }
// }
// }
// }
// }
// }
// }
return 0;
}
}
else
{ // 处理超时
disconnect(pReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
pReply->abort();
pReply->deleteLater();
qDebug()<<"QNetworkReply Timeout String : " << finalPath;
return -1;
}
return 0;
}
标签:Qt,pReply,谷歌,request,timer,API,QString,data,loop 来源: https://blog.csdn.net/qq_36653749/article/details/110931697