【C++使用HTTPLIB库调用百度翻译API代码】

C++使用HTTPLIB库调用百度翻译API代码

代码如下:

//需要安装httplib,openssl
//本代码使用json库进行网页内容解析,如直接使用,请安装json库,也可自行选择其他内容解析方式
#include "httplib.h"
#include <stdio.h>
//#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
#include "json.h"
typedef Json::Writer JsonWriter;
typedef Json::Reader JsonReader;
typedef Json::Value  JsonValue;

//输入:需要翻译的英文单词,string类型
//输出:翻译后的中文结果,string类型
std::string PlaceNameTranslation(std::string tenStr)
{
	if (tenStr.length() > 0)
		if (isalpha(tenStr[0]))
		{
			//百度API的主页网址
			std::string HTTPURL = "http://api.fanyi.baidu.com";
			std::string temHTTPURL = HTTPURL;
			//处理网址:2015063000000001为个人的百度翻译ID(请替换为您的appid),12345678为个人百度翻译密钥,(请替换为您的密钥)
			int a = rand();
			std::string salt = to_string(a);  //随机码
			std::string sign = "2015063000000001"+ tenStr+ salt+"12345678";   
			//sign值进行MD5加密,并转换成16进制
			unsigned char md[16];
			MD5((unsigned char*)sign.c_str(), sign.length(), md);
			string result = "";
			char tmp[3] = { '\0' }, buf[33] = { '\0' };
			for (int i = 0; i < 16; i++) {
				sprintf(tmp, "%2.2x", md[i]);
				strcat(buf, tmp);
			}
			sign = buf;
			//网址后缀
			std::string temURL = "/api/trans/vip/translate?appid=2015063000000001&q="+ tenStr+"&from=en&to=zh&salt="+ salt+"&sign="+ sign;
			temURL = String_TO_UTF8(temURL);
			httplib::Client cli(temHTTPURL);   //"nominatim.terminus.plus"
			//获取网址信息
			if (auto res = cli.Get(temURL.c_str())) {
				if (res->status == 200) {
					std::string strInfoAll = res->body;
					strInfoAll = UTF8_To_String(strInfoAll);
					Json::Reader Reader;
					Json::Value root;
					Reader.parse(strInfoAll, root);
					int intRootSize = root.size();
					if (intRootSize <= 0)
					{
						std::cout << "ERROR: Baidu translation " << tenStr << "failed !!!!" << std::endl;
					}
					if (intRootSize > 0)
					{
						std::string tem = root["from"].asString();
						std::string cNPlaceName = root["trans_result"][0]["dst"].asString();
						cNPlaceName = UTF8_To_String(cNPlaceName);
						return cNPlaceName;
					}
				}
			}		
		}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个httplib post示例代码C++版本: #include <iostream> #include <sstream> #include <string> #include <ctime> #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <vector> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> std::string createRequestBody(const std::string& data) { std::ostringstream request; request << "POST /upload HTTP/1.1\r\n"; request << "Host: example.com\r\n"; request << "Content-Type: application/x-www-form-urlencoded\r\n"; request << "Content-Length: " << data.length() << "\r\n\r\n"; request << data; return request.str(); } int main() { int clientSocket = socket(AF_INET, SOCK_STREAM, 0); if (clientSocket == -1) { std::cout << "Failed to create socket." << std::endl; return 1; } // 连接到服务器 sockaddr_in serverAddress{}; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(80); serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(clientSocket, reinterpret_cast<struct sockaddr*>(&serverAddress), sizeof(serverAddress)) != 0) { std::cout << "Failed to connect to the server." << std::endl; return 1; } // 准备请求体 std::string requestData = "key1=value1&key2=value2"; // 创建请求 std::string requestBody = createRequestBody(requestData); // 发送请求 if (send(clientSocket, requestBody.c_str(), requestBody.length(), 0) < 0) { std::cout << "Failed to send the request." << std::endl; } // 接收响应 char serverResponse[4096]; memset(serverResponse, 0, sizeof(serverResponse)); if (recv(clientSocket, serverResponse, sizeof(serverResponse), 0) < 0) { std::cout << "Failed to receive the server's response." << std::endl; } // 处理响应 std::cout << "Server Response: " << std::endl; std::cout << serverResponse << std::endl; // 关闭连接 close(clientSocket); return 0; } 以上代码实现了一个简单的httplib post请求的发送和接收响应过程。首先,它创建了一个套接字来进行与服务器的连接。然后,它构造了HTTP请求的请求体,并将其发送到服务器。之后,它接收来自服务器的响应,并将其打印到控制台上。最后,它关闭了套接字来终止与服务器的连接。在实际使用时,你需要根据实际情况修改服务器地址、端口以及请求体的内容。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值