Libcurl C++使用multi接口获取HTTP响应码返回0的排查求助
问题根因
CURLINFO_RESPONSE_CODE是请求执行完成后才会被填充的属性,你将读取响应码的逻辑放在了setup函数中——此时刚初始化easy handle,还没发送请求、也没有收到服务端响应,拿到的自然是默认初始化值0。
修复方案
调整curl_easy_getinfo的调用时机到所有请求执行完成之后、easy handle清理之前即可。
修改后完整代码
#include <iostream> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/time.h> #include <unistd.h> #include <curl/curl.h> #include <curl/mprintf.h> #ifndef CURLPIPE_MULTIPLEX #define CURLPIPE_MULTIPLEX 0 #endif struct transfer { CURL *easy; unsigned int num; FILE *out; }; #define NUM_HANDLES 1000 size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) { return size * nmemb; } static void setup(struct transfer *t, int num) { CURL *hnd; hnd = t->easy = curl_easy_init(); /* set the same URL */ curl_easy_setopt(hnd, CURLOPT_URL, "https://httpstat.us/200"); curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, write_data); /* HTTP/2 please */ curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); /* we use a self-signed test server, skip verification during debugging */ curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L); #if (CURLPIPE_MULTIPLEX > 0) /* wait for pipe connection to confirm */ curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); #endif } int main(int argc, char **argv) { struct transfer trans[NUM_HANDLES]; CURLM *multi_handle; int i; int still_running = 0; /* keep number of running handles */ int num_transfers; if(argc > 1) { /* if given a number, do that many transfers */ num_transfers = atoi(argv[1]); if((num_transfers < 1) || (num_transfers > NUM_HANDLES)) num_transfers = 3; /* a suitable low default */ } else num_transfers = 3; /* suitable default */ /* init a multi stack */ multi_handle = curl_multi_init(); for(i = 0; i < num_transfers; i++) { setup(&trans[i], i); /* add the individual transfer */ curl_multi_add_handle(multi_handle, trans[i].easy); } curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); do { CURLMcode mc = curl_multi_perform(multi_handle, &still_running); if(still_running) /* wait for activity, timeout or "nothing" */ mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); if(mc) break; } while(still_running); // 所有请求执行完成后读取响应码 for(i = 0; i < num_transfers; i++) { long response_code; curl_easy_getinfo(trans[i].easy, CURLINFO_RESPONSE_CODE, &response_code); std::cout << "请求" << i+1 << " RESPONSE CODE: " << response_code << std::endl; } for(i = 0; i < num_transfers; i++) { curl_multi_remove_handle(multi_handle, trans[i].easy); curl_easy_cleanup(trans[i].easy); } curl_multi_cleanup(multi_handle); return 0; }
运行验证
用原编译命令g++ test.cpp -lcurl -o test编译后运行,即可看到每个请求都打印出200响应码。
内容的提问来源于stack exchange,提问作者p.luck
相关产品推荐
相关产品推荐

