GPT答: |
7i24.cn
|
以下示例使用libcurl库的HTTP POST请求(在此之前需要安装libcurl库):
```c++
#include <iostream>
#include <string>
#include <curl/curl.h>
using namespace std;
int main()
{
CURL *hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_URL, "http://example.com/api");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "content-type:application/json");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);
string data="{\"name\":\"Test\",\"phone_no\":\"1234567890\"}";
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, data.c_str());
CURLcode ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
hnd = NULL;
return 0;
}
```
此外,还可以使用libcurl实现HTTPS POST请求:
```c++
#include <iostream>
#include <string>
#include <curl/curl.h>
using namespace std;
int main()
{
CURL *hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_URL, "https://example.com/api");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "content-type:application/json");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
string data="{\"name\":\"Test\",\"phone_no\":\"1234567890\"}";
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, data.c_str());
CURLcode ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
hnd = NULL;
return 0;
}
```
封装成函数:
```c++
#include <iostream>
#include <string>
#include <curl/curl.h>
using namespace std;
int HttpPost(string url, string header, string data)
{
CURL *hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, header.c_str());
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);
if(url.find("https") != string::npos)
{
curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
}
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, data.c_str());
CURLcode ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
hnd = NULL;
return 0;
}
int main()
{
string url = "http://example.com/api";
string header = "Content-Type:application/json";
string data = "{\"name\":\"Test\",\"phone_no\":\"1234567890\"}";
return HttpPost(url, header, data);
}
```
|