libcurl实现post请求
时间: 2023-12-23 18:04:25 浏览: 91
libcurl是一个使用广泛的http请求库,可以方便地实现http post请求。对于普通的post请求,一般的post请求格式是Content-Type: application/x-www-form-urlencoded。对应的代码如下:
```
CURL *curl = curl_easy_init();
if (NULL == curl) {
//do something
}
string strUrl = "www.host.com/test.php";
string postret;
string strPostData = "op=op1&op2=op2";
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &postret);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteCallback);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPostData.c_str());
curl_easy_perform(curl);
```
对于复杂的post请求,post数据部分必须为json格式。对应的代码如下:
```
CURL *curl = curl_easy_init();
if (NULL == curl) {
//do something
}
string url = "www.test.com/test.php";
string strPostData = "{\"key\":\"value\"}";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_slist *plist = curl_slist_append(NULL, "Content-Type:application/json;charset=UTF-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, plist);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &postret);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteCallback);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPostData.c_str());
curl_easy_perform(curl);
```
对于特殊的get请求,可以使用curl_easy_setopt函数设置CURLOPT_HTTPGET选项为1。
阅读全文