前言:最近接手了一个C++写的身份证识别的服务器, 要求在给客户端返回数据的同时也要反馈一份给实名认证系统, 以便校验.
本文使用的是curl实现简单的网络请求, 在项目中导入curllibcurl.dll, libcurl.lib, 具体就不说了, 直接说代码, 另外吐槽一下, 用惯了Xcode, 这个BCB用的我实在难受.
HttpQuestion.h
/**
* @author: HanshuaiWu
* @className: THttpQuestion
* @description: 网络请求类
* @createTime: 2018/11/6
*/
class THttpQuestion
{
public:
void SendHttpUrl(IDCardInfo card); // 发送网络请求
AnsiString Url; // 网络请求网址
private:
TTrace mTrace; // 输出对象
};
HttpQuestion.cpp
/**
* @author: HanshuaiWu
* @methodsName: SendHttpUrl
* @description: 发送网络请求
* @param: card:身份证结构体
* @return: 无返回值
* @createTime: 2018/11/6
*/
void THttpQuestion::SendHttpUrl(IDCardInfo card)
{
mTrace.Initialize ("HttpStatus");
CURL *curl;
long rsp_code = 0;
CURLcode curl_code;
// 得到easy interface型指针
curl = curl_easy_init();
if(curl) {
// 这里对参数进行utf8编码(AnsiToUtf8()), 然后再进行中文转码(curl_easy_escape()), 有很多参数, 所以只写两个, 剩下的就不写了
char *name = curl_easy_escape(curl, AnsiToUtf8(card.name).c_str(), AnsiToUtf8(card.name).Length());
card.name = name;
curl_free(name);
char *sex = curl_easy_escape(curl, AnsiToUtf8(card.sex).c_str(), AnsiToUtf8(card.sex).Length());
card.sex = sex;
curl_free(sex);
// 转码完, 拼接网址(使用你要请求的网址)
AnsiString str = "http://"+iniTHttpQuestion.Url+"?UUID="+ card.UUID+ "&timeTag=" + card.timeTag + "&cardNo=" + card.cardNo + "&certType=" + card.certType + "&name=" + card.name + "&sex=" +card.sex + "ðnicity=" +card.ethnicity + "&birth=" + card.birth + "&address=" + card.address + "&authority=" + card.authority + "&period=" + card.period + "&dn=" + card.dn + "&nfcSignature=" + card.nfcSignature;
mTrace.Trace ("请求:=%s", str);
char *url = str.c_str();
// 设置传输选项
curl_easy_setopt(curl, CURLOPT_URL, url);
/* example.com is redirected, so we tell libcurl to follow redirection */
// 设置的传输选项, 实现回调函数以完成用户特定任务
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
// 函数完成传输任务
curl_code = curl_easy_perform(curl);
if(curl_code != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(curl_code));
}
// 响应状态码
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rsp_code);
if (rsp_code == 200 && curl_code != CURLE_ABORTED_BY_CALLBACK)
{
mTrace.Trace ("请求成功, 状态码=%d", rsp_code);
}
else
{
mTrace.Trace ("请求失败, 状态码=%d", rsp_code);
}
// 释放内存
curl_easy_cleanup(curl);
}
}
喜欢的小伙伴点个喜欢或关注吧, 你们的鼓励是我前进的动力