curl发送json数据
时间: 2024-05-21 22:09:12 浏览: 130
Curl是一个非常流行的命令行工具和库,可用于传输数据,其中包括使用HTTP协议发送和接收数据。如果你想要使用Curl发送JSON数据,可以按照以下步骤操作:
1. 准备好要发送的JSON数据,将其保存为字符串或从文件中读取。例如,以下是一个JSON字符串:
```
{"name": "John Smith", "age": 30, "city": "New York"}
```
2. 使用Curl库中的curl_easy_init()函数初始化Curl句柄。
```
CURL *curl;
curl = curl_easy_init();
```
3. 设置请求的URL地址。例如:
```
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api");
```
4. 设置请求的HTTP方法,这里我们使用POST方法。
```
curl_easy_setopt(curl, CURLOPT_POST, 1L);
```
5. 设置请求头,指定Content-Type为application/json。
```
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
```
6. 设置请求体,将JSON数据作为请求体发送。
```
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"name\": \"John Smith\", \"age\": 30, \"city\": \"New York\"}");
```
7. 执行HTTP请求,将响应保存在一个缓冲区中。
```
CURLcode res;
char *response = NULL;
size_t response_size = 0;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
res = curl_easy_perform(curl);
```
8. 处理响应数据。在这里,我们将响应数据打印出来。
```
printf("%s\n", response);
```
9. 释放Curl句柄和请求头。
```
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
```
完整的代码示例如下:
```
#include <stdio.h>
#include <curl/curl.h>
size_t write_memory_callback(void *ptr, size_t size, size_t nmemb, void *data) {
size_t realsize = size * nmemb;
char **mem = (char **)data;
*mem = realloc(*mem, response_size + realsize + 1);
if (*mem == NULL) {
printf("out of memory\n");
return 0;
}
memcpy(*mem + response_size, ptr, realsize);
response_size += realsize;
(*mem)[response_size] = 0;
return realsize;
}
int main(void) {
CURL *curl;
CURLcode res;
char *response = NULL;
size_t response_size = 0;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api");
curl_easy_setopt(curl, CURLOPT_POST, 1L);
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"name\": \"John Smith\", \"age\": 30, \"city\": \"New York\"}");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
printf("%s\n", response);
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
free(response);
}
curl_global_cleanup();
return 0;
}
```
阅读全文