gpt4 book ai didi

c - libcurl:http 响应状态代码始终为 NULL?

转载 作者:可可西里 更新时间:2023-11-01 17:04:38 24 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

... but when the server is not reachable I'm receiving a CURLE_HTTP_RETURNED_ERROR error.In this scenario I'm always getting a CURLE_COULDNT_CONNECT curl error and the HTTP response code is 0.

如果服务器不可访问且连接失败,检查响应代码甚至没有意义。 response codeHTTP 响应的属性。它记录在 HTTP 服务器发回的部分 HTTP 响应(status line)中,以回复 libcurl 代表您发送的 HTTP 请求。如果没有连接,说明服务器没有收到你的请求,没有响应可言!

Based on my requirement I want the HTTP response code.

如果没有连接,则没有响应 - 因此没有响应代码。

在这种情况下,您可以将 local responseCode 变量设置为 -1 以指示连接失败:

*responseCode = -1;

关于c - libcurl:http 响应状态代码始终为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54233381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com