文|Seraph
凡事都有原因
接触百度翻译API,主要是想用c++实现一个和TTS技术结合的翻译软件;
当然,还有一个原因就是200万字以内API调用免费。
#include
#include
#include
#include
#include
#pragma comment(lib,"libcurl.lib")
#pragma comment(lib,"libcurld_imp.lib")
#pragma comment(lib,"libcrypto.lib")
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl) {
char myurl[1000] = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
char *appid = "20170520000048515"; //replace myAppid with your own appid
char *q = "pear"; //replace apple with your own text to be translate, ensure that the input text is encoded with UTF-8!
char *from = "en"; //replace en with your own language type of input text
char *to = "zh"; //replace zh with your own language type of output text
char salt[60];
int a = rand();
sprintf_s(salt, "%d", a);
char *secret_key = "sERmjSSdTNowRYvEABOr"; //replace mySecretKey with your own mySecretKey
char sign[120] = "";
strcat_s(sign, appid);
strcat_s(sign, q);
strcat_s(sign, salt);
strcat_s(sign, secret_key);
printf("%s\n", sign);
unsigned char md[16];
int i;
char tmp[3] = { '\0' }, buf[33] = { '\0' };
MD5((unsigned char *)sign, strlen(sign), md);
for (i = 0; i < 16; i++) {
sprintf_s(tmp, "%2.2x", md[i]);
strcat_s(buf, tmp);
}
printf("%s\n", buf);
strcat_s(myurl, "appid=");
strcat_s(myurl, appid);
strcat_s(myurl, "&q=");
strcat_s(myurl, q);
strcat_s(myurl, "&from=");
strcat_s(myurl, from);
strcat_s(myurl, "&to=");
strcat_s(myurl, to);
strcat_s(myurl, "&salt=");
strcat_s(myurl, salt);
strcat_s(myurl, "&sign=");
strcat_s(myurl, buf);
printf("%s\n", myurl);
//设置访问的地址
curl_easy_setopt(curl, CURLOPT_URL, myurl);
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
long responseCode = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
主要添加了lib,以及将不安全函数strcat、sprintf都换成strcat_s、sprintf_s。
同时将
MD5((unsigned char *)sign, strlen((unsigned char *)sign), md);
换成
MD5((unsigned char *)sign, strlen(sign), md);
4.为工程添加之前生成的libcurl及openssl的库文件
这里用到的相关版本号:openssl-1.1.0e、curl-7.26.0
lib主要用到libcurl.lib、libcurld_imp.lib、libcrypto.lib
同时,记得将相关dll放置exe文件目录下,如libcurld.dll、libcrypto-1_1.dll。
接下来就可以将代码修改成自己想要的功能样子了,也可以按自己设计再添加一些界面和功能。
凡人皆有一死!------《权利的游戏》