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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
|
//
// Created by lvwei on 2023/12/18.
//
#include "CurlTest.h"
#include <curl/curl.h>
#include <iostream>
//注意路径,也可以在CMakeLists.txt文件中加入lib目录包含,include_directories(${CURL_INCLUDE_DIR}
// lib),即可省略下方lib目录
#include "lib/rapidjson/document.h"
#include "lib/rapidjson/writer.h"
#include "lib/rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
static const char *KAPIHome = "https://www.baidu.com";
static const char *KAPIUserLogin = "http://127.0.0.1:8081/user/login";
CurlTest::CurlTest()
{
}
// 回调函数,用于处理响应头
size_t header_callback(void *buffer, size_t size, size_t nmemb, void *userData) {
// 计算存储数据的大小
size_t real_size = size * nmemb;
auto* data = (std::string*)userData;
// 将数据拼接到字符串中
data->append(static_cast<char*>(buffer), real_size);
cout<<data<<endl;
return real_size;
}
// 回调函数,用于处理响应数据
size_t response_data_callback(void *buffer, size_t size, size_t nmemb, std::string *data) {
// 计算存储数据的大小
size_t real_size = size * nmemb;
// 将数据拼接到字符串中
data->append(static_cast<char*>(buffer), real_size);
return real_size;
}
void CurlTest::handleCurlGetJsonParse(std::string& jsonData) {
Document document;
document.Parse(jsonData.c_str());
// 检查解析是否成功
if (document.HasParseError()) {
std::cout << "解析JSON时出错" << std::endl;
} else {
// 从解析的JSON中提取数据
if (document.IsObject()) {
std::string message = document["message"].GetString();
// 输出解析结果
std::cout << "message: " << message << std::endl;
} else {
std::cout << "无效的JSON格式" << std::endl;
}
}
}
void CurlTest::testCurlhttpGet() {
CURL* curl = curl_easy_init();
if (curl) {
// 设置请求的 URL
curl_easy_setopt(curl, CURLOPT_URL, KAPIHome);
//获取响应头信息
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
std::string responseHeader;
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeader);
// 存储响应数据的字符串
std::string responseData;
// 设置写入响应数据的目标
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, response_data_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseData);
// 执行 HTTP 请求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
} else {
long response_code;
// 获取HTTP状态码
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
char *contentType = nullptr;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &contentType);
cout<<"response code:"<<response_code<<endl;
cout<<"response header:"<<responseHeader<<endl;
// 响应数据存储在 responseData 中,可以进行解析或处理
cout << "Response received:" << responseData<<std::endl;
// handleCurlGetJsonParse(responseData);
}
// 清理 curl 资源
curl_easy_cleanup(curl);
} else {
std::cerr << "Failed to initialize libcurl" << std::endl;
}
}
/*
curl -X 'POST' \
'http://127.0.0.1:8081/user/login' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "ksnowlv",
"age": 0,
"phone": "15210795183",
"verification_code": "123456"
}'
*/
void CurlTest::testCurlHttpPost() {
// 创建一个JSON文档
Document document;
document.SetObject();
Document::AllocatorType& allocator = document.GetAllocator();
// 添加JSON字段
document.AddMember("name", "ksnowlv", allocator);
document.AddMember("age", 0, allocator);
document.AddMember("phone", "15210795183", allocator);
document.AddMember("verification_code", "123456", allocator);
// 将JSON文档转换为字符串
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
document.Accept(writer);
std::string jsonStr = buffer.GetString();
// 输出生成的JSON字符串
std::cout << "生成的JSON字符串:" << jsonStr << std::endl;
CURL* curl = curl_easy_init();
if (curl) {
// 设置请求的URL
curl_easy_setopt(curl, CURLOPT_URL, KAPIUserLogin);
// 设置请求头
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 设置请求数据
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonStr.c_str());
// 设置请求为POST
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
std::string responseHeader;
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeader);
// 设置写入响应数据的目标
std::string responseData;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, response_data_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseData);
// 执行请求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
} else {
long response_code;
// 获取HTTP状态码
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
cout<<"response code:"<<response_code<<endl;
cout<<"response header:"<<responseHeader<<endl;
// 响应数据存储在 responseData 中,可以进行解析或处理
cout << "Response received:" << responseData<<std::endl;
//handleCurlPostJsonParse(responseData);
this->handleCurlPostJsonParse(responseData);
}
// 释放curl句柄和headers
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
} else {
std::cerr << "初始化curl失败" << std::endl;
}
}
void CurlTest::handleCurlPostJsonParse(const std::string& json) {
Document document;
document.Parse(json.c_str());
// 检查解析是否成功
if (document.HasParseError()) {
std::cout << "解析JSON时出错" << std::endl;
} else {
// 从解析的JSON中提取数据
if (document.HasMember("code") && document["code"].IsInt()) {
int code = document["code"].GetInt();
std::cout << "返回的code: " << code << std::endl;
}
if (document.HasMember("message") && document["message"].IsString()) {
std::string message = document["message"].GetString();
std::cout << "返回的message: " << message << std::endl;
}
if (document.HasMember("data") && document["data"].IsObject()) {
const Value& data = document["data"];
if (data.HasMember("userid") && data["userid"].IsString()) {
std::string userId = data["userid"].GetString();
std::cout << "返回的userid: " << userId << std::endl;
}
if (data.HasMember("token") && data["token"].IsString()) {
std::string token = data["token"].GetString();
std::cout << "返回的token: " << token << std::endl;
}
}
}
}
|