首先要声明header的结构体变量,然后设置对应header值,最后将其设置到curl结构体中
//声明
CURL *curl;
struct curl_slist *headers = NULL;
//赋值header值
headers = curl_slist_append(headers, "Host: 0xz.sz.qcloud.com");
headers = curl_slist_append(headers, "yousa3: zym");
//设置header
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
//声明url
string url = "http://10.54.69.29:80/test/usr/loveqiqian";
//指定url
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
//发送http请求
res = curl_easy_perform(curl);
这里发送的请求是POST请求,通过如下代码设置的是POST请求
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
如果没有指定contenttype,那么contenttype默认是post的标准表单格式,application/x-www-form-urlencoded
设置body是如下代码:
//先用char[] 准备好要发送的body字符串
char hello[12] = "a=hello";
//设置body长度以及内容
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(hello));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, hello);
//然后就可以使用easy_perform接口发送了。
res获取到的就是HTTP响应码
res = curl_easy_perform(curl);
//声明
string header;
string result;
//设置
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &write_data);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
//write_data函数是这样
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp){
char *d = (char*)buffer;
string *b = (string*)(userp);
int result = 0;
if (b != NULL){
b->append(d, size*nmemb);
result = size*nmemb;
}
return result;
}
PS:HEAD请求的响应是没有body的,需要额外设置一行
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
#include
#include
#include
#include
using namespace std;
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);
int main() {
cout<<"hello world" << endl;
CURL *curl;
CURLcode res;
curl = curl_easy_init();
string url = "http://10.54.69.29:80/test/usr/loveqiqian";
string header;
string result;
struct curl_slist *headers = NULL;
char hello[12] = "a=hello";
headers = curl_slist_append(headers, "Host: 0xz.sz.qcloud.com");
headers = curl_slist_append(headers, "yousa3: zym");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(hello));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, hello);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &write_data);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
res = curl_easy_perform(curl);
cout << header << endl << endl;
cout << result << endl;
cout << res << endl;
curl_easy_cleanup(curl);
return 0;
}
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp){
char *d = (char*)buffer;
string *b = (string*)(userp);
int result = 0;
if (b != NULL){
b->append(d, size*nmemb);
result = size*nmemb;
}
return result;
}