作者:feng2502863897 | 来源:互联网 | 2023-09-23 21:09
下面的代码编译并打印响应。
我的问题是:作为响应,一个字符串表示一个对象,我如何将“ res”转换为字符串或直接转换为json对象?
#include
#include
#include
int main(int argc,char **argv) {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl,CURLOPT_CUSTOMREQUEST,"GET");
curl_easy_setopt(curl,CURLOPT_URL,"http://localhost:8080/system/genpass");
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L);
curl_easy_setopt(curl,CURLOPT_DEFAULT_PROTOCOL,"https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers,"length: 20");
headers = curl_slist_append(headers,"numbers: true");
curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);
res = curl_easy_perform(curl);
printf("%u",res);
}
curl_easy_cleanup(curl);
}
您不能简单地将函数的返回代码转换为字符串。
它们没有任何关系。
相反,您需要直接处理接收到的数据。
为此,您需要注册一个可以处理数据的回调函数。
cURL manual中对此进行了说明。
示例:
typedef struct {
unsigned char *buffer;
size_t len;
size_t buflen;
} get_request;
#define CHUNK_SIZE 2048
size_t write_callback(char *ptr,size_t size,size_t nmemb,void *userdata)
{
size_t realsize = size * nmemb;
get_request *req = (get_request *) userdata;
printf("receive chunk of %zu bytes\n",realsize);
while (req->buflen len + realsize + 1)
{
req->buffer = realloc(req->buffer,req->buflen + CHUNK_SIZE);
req->buflen += CHUNK_SIZE;
}
memcpy(&req->buffer[req->len],ptr,realsize);
req->len += realsize;
req->buffer[req->len] = 0;
return realsize;
}
int main(int argc,char **argv) {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
get_request req = {.buffer = NULL,.len = 0,.buflen = 0};
if (curl) {
curl_easy_setopt(curl,CURLOPT_CUSTOMREQUEST,"GET");
curl_easy_setopt(curl,CURLOPT_URL,"https://example.com");
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L);
curl_easy_setopt(curl,CURLOPT_DEFAULT_PROTOCOL,"https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers,"length: 20");
headers = curl_slist_append(headers,"numbers: true");
curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);
req.buffer = malloc(CHUNK_SIZE);
req.buflen = CHUNK_SIZE;
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_callback);
curl_easy_setopt(curl,CURLOPT_WRITEDATA,(void *)&req);
res = curl_easy_perform(curl);
printf("Result = %u\n",res);
printf("Total received bytes: %zu\n",req.len);
printf("Received data:/n%s\n",req.buffer);
free(req.buffer);
}
curl_easy_cleanup(curl);
}
输出:
receive chunk of 1256 bytes
Result = 0
Total received bytes: 1256
Received data:
Example Domain
This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.
More information...
完成GET请求后,您可以访问req->buffer
中的数据并解析JSON对象或任何其他数据。
需要添加错误检查(针对realloc
等)。
我使用了一种方法,该方法能够处理任何数量的接收到的块中的任何长度的内容。
如果知道所需内容的长度,则可以使用固定大小的缓冲区。
在我的示例中可以看到,下载完成后用户数据结构仍然存在,并且可以在curl_easy_perform
返回之后派生内容。