3

我通过 C 代码中的 libcurl 向 POST 请求发送了不正确的 URL。服务器发回 400 以及包含有关请求被拒绝原因的详细信息的响应。在 libcurl 我可以看到错误代码:

res CURLcode    CURLE_HTTP_RETURNED_ERROR

我还可以通过以下方式查看协议错误:

char errbuf[CURL_ERROR_SIZE];
errbuf[0] = 0;
curl_easy_setopt(vc->curl, CURLOPT_ERRORBUFFER, errbuf);
/* Perform the request, resCode will get the return code */
CURLcode resCode = curl_easy_perform(vc->curl);


errbuf  char [256]  "The requested URL returned error: 400 Bad Request" 

我真正想访问的是响应的正文。服务器将详细的错误信息放在那里,说明它拒绝请求的原因:

[
    {
        "code": "io.myorg.bad.request",
        "message": "Unrecognized query parameter 'count' with value: true.",
        "params": []
    }
]

我通过以下方式设置了读写回调函数:

/* ask curl to let us know if we get a 400 or higher */
curl_easy_setopt(vc->curl, CURLOPT_FAILONERROR, 1L);

curl_easy_setopt(vc->curl, CURLOPT_HTTPHEADER, vc->slist);

/* we want to use our own read/write function */
curl_easy_setopt(vc->curl, CURLOPT_READFUNCTION, read_callback);
curl_easy_setopt(vc->curl, CURLOPT_WRITEFUNCTION, write_callback);

/* pointer to pass to our callback functions */
curl_easy_setopt(vc->curl, CURLOPT_READDATA, vc);
curl_easy_setopt(vc->curl, CURLOPT_WRITEDATA, vc); 

在这种情况下不会调用它们。我如何在响应消息中获取 json?

4

1 回答 1

2

启用该CURLOPT_FAILONERROR选项可防止在检测到错误时调用写入回调。

于 2018-06-23T03:14:09.590 回答