c - libcurl:http响应状态码总是NULL?
问题描述
我正在使用 libcurl 7.29.0。
当服务器运行时,我所有的测试用例都可以正常工作,但是当服务器无法访问时,我会收到CURLE_HTTP_RETURNED_ERROR
错误消息。
在这种情况下,我总是收到CURLE_COULDNT_CONNECT
curl 错误,并且 HTTP 响应代码是0
.
根据我的要求,我想要 HTTP 响应代码。请提出一些解决方案提前谢谢。
下面附上了我用来发布数据的 API。
int http_curl_post_response(char *url, char *post_data, char *response,
long int *responseCode) {
CURL *ps_curl;
CURLcode curl_status = CURLE_OK;
struct curl_slist *headers = NULL; /* http headers to send with request */
/* get a curl handle */
ps_curl = curl_easy_init();
if (ps_curl) {
/* set content type */
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
/* This is to intialize respone from curl */
http_curl_respone ps_response;
curl_easy_setopt(ps_curl, CURLOPT_URL, url);
curl_easy_setopt(ps_curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(ps_curl, CURLOPT_POSTFIELDS, post_data);
curl_easy_setopt(ps_curl, CURLOPT_POSTFIELDSIZE, -1L);
curl_easy_setopt(ps_curl, CURLOPT_FOLLOWLOCATION, 1L);
/* This is to read response from curl */
curl_easy_setopt(ps_curl, CURLOPT_WRITEFUNCTION, write_response_json);
init_response(&ps_response);
if (ps_response.pi1_response == NULL) {
i4_curl_status = MEM_ALLOC_ERROR;
goto HTTP_CURL_ERROR;
}
curl_easy_setopt(ps_curl, CURLOPT_WRITEDATA, &ps_response);
curl_easy_setopt(ps_curl, CURLOPT_FAILONERROR, 1L);
/* Perform the request, i4_curl_status will get the return code */
curl_status = curl_easy_perform(ps_curl);
if (curl_status != CURLE_OK) {
if (curl_status == CURLE_HTTP_RETURNED_ERROR) {
curl_easy_getinfo(ps_curl, CURLINFO_RESPONSE_CODE,
responseCode);
/* always cleanup */
curl_easy_cleanup(ps_curl);
}
goto HTTP_CURL_ERROR;
} else {
memcpy(response, ps_response.pi1_response, ps_response.s_len);
response[ps_response.s_len] = '\0';
}
/* always cleanup */
curl_easy_cleanup(ps_curl);
/* free headers */
curl_slist_free_all(headers);
HTTP_MEM_ERROR:
if (ps_response.pi1_response) free(ps_response.pi1_response);
} else {
curl_status = CURLE_FAILED_INIT;
}
HTTP_CURL_ERROR:
return curl_status;
}
解决方案
...但是当服务器无法访问时,我收到 CURLE_HTTP_RETURNED_ERROR 错误。在这种情况下,我总是收到 CURLE_COULDNT_CONNECT curl 错误,并且 HTTP 响应代码为 0。
如果服务器无法访问并且连接失败,则检查响应代码甚至没有意义。响应代码是HTTP 响应的一个属性。它记录在 HTTP 响应(状态行)的一部分中,HTTP 服务器发回该响应以回复libcurl
代表您发送的 HTTP 请求。如果没有连接,服务器没有收到你的请求,也没有响应可言!
根据我的要求,我想要 HTTP 响应代码。
如果没有连接,则没有响应 - 因此没有响应代码。
在这种情况下,您可以将本地 responseCode
变量设置-1
为指示连接失败:
*responseCode = -1;
推荐阅读
- mysql - 我如何将列位置更新到具有多个条件mysql的表中
- c# - 发送请求时出错
- c++ - 如何单击打开 C++ 制作的 exe 文件?
- python-3.x - 计算pandas中此列的前3个月、6个月、1年和2年的pandas列均值的滞后特征
- dynamic - SSRS 和动态枢轴:分组
- python - 使用迭代读取和写入 csv
- html - How to pass data from Navigation Component to Home Component in React?
- python - 如何使用 Redis Queue 将带有参数的函数排入队列?
- javascript - 提交时表单输入日期范围以过滤其余 api
- html - Live Server - Live Reload 功能不适用于具有不同目录路径的 WSL