C++ libcurl HTTP POST请求向服务器发送json数据

本文只是记录作者学习c++ http已post请求发送数据

编译准备

选择一个第三方库,我这里用的是 libcurl

libcurl下载地址

1.下载curl源代码,下载地址版本(7.73.0):libcurl(7.73.0)
如果想选择版本:链接:libcurl地址

编译生成三方库文件

解压文件之后找到 curl-7.73.0\projects\Windows\VC15\lib文件夹下的 libcurl.vcxproj 文件,通过编译器打开,现支持编译器版本如下
支持编译器版本
打开工程之后设置为LIB Release/LIB Debug
我所使用的是Win32

lib文件设置编译生成的lib文件在 curl-7.73.0\build\Win32\VC15\LIB Release 该文件下

工程属性设置

命令行添加 -D CURL_STATICLIB
命令行设置添加之后会在附加选项同步

附加选项确认

代码

需包含的库

1
2
3
4
5
6
7
8
9
10
11
12
#pragma comment ( lib, "ws2_32.lib" )
#pragma comment ( lib, "winmm.lib" )
#pragma comment ( lib, "wldap32.lib" )
#pragma comment(lib, "Advapi32.lib")

#ifdef _DEBUG
#pragma comment(lib,"libcurld.lib")
#else
#pragma comment(lib,"libcurl.lib")
#endif

#include "../curl/curl.h"

构建HTTP报文头

我在这里是通过postman获取的所发送的报文头
先用postman发送测试的报文

通过postman发送测试报文然后点击Code就可以获取到你所需要的报文头
c发送json格式报文代码

代码生成

调用函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
int HttpPost(string host, string send, string & resp)
{
    CURL *curl;
    CURLcode res;
    char tmp_str[256] = { 0 };
    std::stringstream out;

    //HTTP报文头  
    struct curl_slist* headers = NULL;

    char url[50] = { 0 };
    strcpy(url, host.c_str());
    //AfxMessageBox(_T("开始"));
    curl = curl_easy_init();

    if (curl)
    {
        //构建json
        string jsonout = send;
        char sendchar[4096] = { 0 };
        char ret[4096] = { 0 };
        strcpy(sendchar, jsonout.c_str());
        GBKtoU8(sendchar, ret);//如果发送报文内没有中文字符则可以不转换
        jsonout = ret;
       
        //设置url
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_easy_setopt(curl, CURLOPT_URL, url);

        //设置http发送的内容类型为JSON
        //构建HTTP报文头  
        AfxMessageBox(StrToCstr(jsonout));

        headers = curl_slist_append(headers, "cache-control:no-cache");
        headers = curl_slist_append(headers, "Content-Type:application/json");
       
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

                                                // 设置要POST的JSON数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonout.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonout.size());//设置上传json串长度,这个设置可以忽略

                                                                      // 设置接收数据的处理函数和存放变量
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);//设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);//设置写数据
        res = curl_easy_perform(curl);//执行

        curl_slist_free_all(headers); /* free the list again */

         resp = out.str();//返回请求值
        char reta[4096] = { 0 };
        UtfToGbk(resp.c_str(), reta);
        resp = reta;
        AfxMessageBox(StrToCstr(resp));

        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    return 0;
}

UTF-8和GBK格式相互转换函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void UtfToGbk(const char* utf8, char * gbk)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len + 1];
    memset(wstr, 0, len + 1);
    MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
    len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
    //char* str = new char[len+1];
    memset(gbk, 0, len + 1);
    //WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
    WideCharToMultiByte(CP_ACP, 0, wstr, -1, gbk, len, NULL, NULL);
    if (wstr) delete[] wstr;

    //return str;
}

void GBKtoU8(char gbkstr[], char *utf8str)
{
    int len_wchart;
    wchar_t *unicode;
    int len_utf8;

    len_wchart = MultiByteToWideChar(CP_ACP, 0, gbkstr, -1, NULL, 0);   //得到GBK=>UTF8后需要字符串长度
    unicode = (wchar_t *)malloc(len_wchart * sizeof(wchar_t)); //分配空间存储UNICODE中间结果
    MultiByteToWideChar(CP_ACP, 0, gbkstr, -1, unicode, len_wchart);        //GBK => UINCODE
    len_utf8 = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, NULL, 0, NULL, NULL);  //UINCODE=>UTF8需要的长度
    WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8str, len_utf8, NULL, NULL);   //UNICODE => UTF8

    free(unicode);
}

如果发送或者接收的报文内有中文字符则需要转换,不然会显示为乱码。
我现在所发送的报文格式UTF-8

结尾

调用函数之后返回的报文,和用postman发送报文返回值一样,则代码完成接口测试通过,再继续整合代码。

本文所参考的为 https://blog.csdn.net/z550449054/article/details/78683976