libcurl c++ get post

本次博主将使用 c++ 操作 libcurl 进行 get post
摘自官网: libcurl是一个免费且易于使用的客户端URL传输库,支持DICT、FILE、FTP、FTPS、GOPHER、GOPHERS、HTTP、HTTPS、IMAP、IMAPS、LDAP、LDAPS、MQTT、POP3、POP3S、RTMP、RTMPS、RTSP、SCP、SFTP、SMB、SMBS、SMTP、SMTPS、TELNET和TFTP。libcurl支持SSL证书、HTTP POST、HTTP PUT、FTP上载、基于HTTP表单的上载、代理、HTTP/2、HTTP/3、cookie、用户+密码身份验证(基本、摘要、NTLM、协商、Kerberos)、文件传输恢复、HTTP代理隧道等
本章节博主将使用 libcurl 完成 get post json post form 操作

源代码放到博文最下方了 o( ̄▽ ̄)ブ

get

服务端代码:

1
2
3
4
5
6
7
8
9
10
11
12
@GetMapping("/getUser")
public User getUserInfo
(
String name,
String address,
@RequestHeader(name = "key1") String key1,
@RequestHeader(name = "key2") String key2
)
{
log.info("name: {} address: {} key1:{} key2:{}", name, address, key1, key2);
return User.builder().age(18).name(name).address(address).createTime(LocalDateTime.now()).build();
}

c++ 代码

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
/**
* get request
* url url地址
* p url参数
* h header参数
* timeoutMs 超时时间
*/
const std::string get(
const std::string& url,
const UrlParams& p = std::map<std::string, std::string>(),
const HeaderParams & h = std::map<std::string, std::string>(),
int timeoutMs = 300
)
{
//超时时间
curl_easy_setopt(libCurl,CURLOPT_TIMEOUT_MS, timeoutMs);

//处理url参数
const char* newUrl = handlerUrl(url, p);
std::string resData;
curl_easy_setopt(libCurl, CURLOPT_WRITEDATA, &resData);
curl_easy_setopt(libCurl, CURLOPT_WRITEFUNCTION, CurlSupport::write_callback);
curl_easy_setopt(libCurl, CURLOPT_URL, newUrl);


//处理header参数
struct curl_slist* headers = curl_slist_append(NULL, "Expect:");;
handlerHeader(h, headers);
curl_easy_setopt(libCurl, CURLOPT_HTTPHEADER, headers);

CURLcode resCode = curl_easy_perform(libCurl);

curl_slist_free_all(headers);

if (CURLE_OK != resCode)
{
throw CurlSupportException(curl_easy_strerror(resCode));
}
else
{
return resData;
}
}

测试调用

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
void testGet()
{
try
{
CurlSupport curl;
//参数
const std::map<std::string, std::string> p =
{
{"name",u8"张三"},
{"address",u8"浙江杭州540."}
};
//header
const std::map<std::string, std::string> h =
{
{"key1","key1key1key1a"},
{"key2","key2key2key2b"}
};

std::string responseStr = curl.get("http://127.0.0.1:8080/getUser",p,h);
std::cout << responseStr <<std::endl;
}
catch (const CurlSupportException& e)
{
std::cout << e.what() << std::endl;
}
}
post json

服务端代码

1
2
3
4
5
6
7
8
9
@PostMapping("/addUser")
public Boolean addUser(
@RequestBody User user,
@RequestHeader(name = "token1") String token1,
@RequestHeader(name = "token2") String token2
) {
log.info("\nuser:{} \n token1:{} token2:{}", user, token1, token2);
return Boolean.TRUE;
}

c++ 代码

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
/**
* post json
* url url地址
* h header参数
* timeoutMs 超时时间
*/
const std::string postJson
(
const std::string& url,
const std::string& jsonStr,
const HeaderParams& h = std::map<std::string, std::string>(),
int timeoutMs = 300
)
{
//超时时间
curl_easy_setopt(libCurl, CURLOPT_TIMEOUT_MS, timeoutMs);

//处理header参数
struct curl_slist* headers = curl_slist_append(NULL, "Expect:");
const std::string jsonHeader = "Content-Type:application/json;charset=UTF-8";
headers = curl_slist_append(headers, jsonHeader.c_str());
handlerHeader(h, headers);
curl_easy_setopt(libCurl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(libCurl, CURLOPT_URL, url.c_str());

std::string resData;

//传递json
curl_easy_setopt(libCurl, CURLOPT_POSTFIELDS, jsonStr.c_str());
curl_easy_setopt(libCurl, CURLOPT_WRITEDATA, &resData);
curl_easy_setopt(libCurl, CURLOPT_WRITEFUNCTION, CurlSupport::write_callback);

CURLcode resCode = curl_easy_perform(libCurl);

curl_slist_free_all(headers);
if (CURLE_OK != resCode)
{
throw CurlSupportException(curl_easy_strerror(resCode));
}
else
{
return resData;
}
}

测试调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void testPostJson()
{
try
{
CurlSupport curl;

//jsonStr
std::string jsonStrr = u8"{\"name\":\"李四\",\"address\":\"上海市654路\",\"age\":6}";

//header
const std::map<std::string, std::string> h =
{
{"token1","abc697"},
{"token2","efv247"}
};

std::string responseStr = curl.postJson("http://127.0.0.1:8080/addUser",jsonStrr, h);
std::cout << responseStr << std::endl;
}
catch (const CurlSupportException& e)
{
std::cout << e.what() << std::endl;
}
}
post form

服务端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@PostMapping("/updateUser")
public Boolean updateUser
(
User user,
@RequestHeader(name = "token1") String token1,
@RequestHeader(name = "token2") String token2,
MultipartFile[] photoList
) throws IOException {

log.info("\nuser: {} \n token1:{} token2:{}", user, token1, token2);

if (null != photoList) {
for (MultipartFile file : photoList) {
log.info(file.getOriginalFilename());
file.transferTo(new File("D:\\temp\\" + file.getOriginalFilename()));
}
}
return Boolean.TRUE;
}

c++ 代码

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
/**
* postForm
* url url地址
* f 表单参数
* h header参数
* timeoutMs 超时时间
*/
const std::string postForm
(
const std::string& url,
const FormParams& f,
const HeaderParams& h = std::map<std::string, std::string>(),
int timeoutMs = 300
)
{
//超时时间
curl_easy_setopt(libCurl, CURLOPT_TIMEOUT_MS, timeoutMs);

//处理header参数
struct curl_slist* headers = curl_slist_append(NULL, "Expect:");;
handlerHeader(h, headers);
curl_easy_setopt(libCurl, CURLOPT_HTTPHEADER, headers);

const char* charUrl = url.c_str();
curl_mime* form = NULL;
curl_mimepart* fieid = NULL;
std::string resData;

//创建表单
form = curl_mime_init(libCurl);

//表单参数
for (auto item : f)
{
std::string name = std::get<0>(item);
std::string value = std::get<1>(item);
boolean isFile = std::get<2>(item);

//判断是否是文件
if (isFile)
{
fieid = curl_mime_addpart(form);
curl_mime_name(fieid, name.c_str());
curl_mime_filedata(fieid, value.c_str());
}else {
fieid = curl_mime_addpart(form);
curl_mime_name(fieid, name.c_str());
curl_mime_data(fieid, value.c_str(), CURL_ZERO_TERMINATED);
}
}

curl_easy_setopt(libCurl, CURLOPT_URL, charUrl);
curl_easy_setopt(libCurl, CURLOPT_MIMEPOST, form);
curl_easy_setopt(libCurl, CURLOPT_WRITEDATA, &resData);
curl_easy_setopt(libCurl, CURLOPT_WRITEFUNCTION, CurlSupport::write_callback);

CURLcode resCode = curl_easy_perform(libCurl);
curl_mime_free(form);

if (CURLE_OK != resCode)
{
throw CurlSupportException(curl_easy_strerror(resCode));
}
else{
return resData;
}
}

测试调用

源代码

服务端代码:
https://github.com/wchar-net/libcurl-cpp-example-server
c++代码
https://github.com/wchar-net/libcurl-cpp-example

具体看源代码吧 o( ̄▽ ̄)ブ