C 从libevent中的HTTP服务器响应获取所有HTTP头

C 从libevent中的HTTP服务器响应获取所有HTTP头,c,http,libevent,C,Http,Libevent,使用libevent执行HTTP请求。我想打印服务器响应中的所有HTTP头,但不确定如何打印 static void http_request_done(struct evhttp_request *req, void *ctx) { //how do I print out all the http headers in the server response } evhttp_request_new(http_request_done,NULL); 我知道我可以像下面这样得到一

使用libevent执行HTTP请求。我想打印服务器响应中的所有HTTP头,但不确定如何打印

static void http_request_done(struct evhttp_request *req, void *ctx) {
    //how do I print out all the http headers in the server response 
}

evhttp_request_new(http_request_done,NULL);
我知道我可以像下面这样得到一个单独的标题,但是我如何得到所有的标题呢

static void http_request_done(struct evhttp_request *req, void *ctx) {
    struct evkeyvalq * kv = evhttp_request_get_input_headers(req);
    printf("%s\n", evhttp_find_header(kv, "SetCookie"));
}

谢谢。

虽然我以前没有任何使用
libevent
库的经验,但我很清楚API不提供此类功能(请参阅其参考资料)。但是,您可以使用
TAILQ\u FOREACH
internal宏编写自己的方法,该宏在
event internal.h
中定义。
evhttp\u find\u头的定义相当简单:

const char *
evhttp_find_header(const struct evkeyvalq *headers, const char *key)
{
    struct evkeyval *header;

    TAILQ_FOREACH(header, headers, next) {
        if (evutil_ascii_strcasecmp(header->key, key) == 0)
            return (header->value);
    }

    return (NULL);
}
您只需从
evkeyval
struct(在
include/event2/keyvalq\u struct.h
中定义)获取
header->key
header->value
条目,而不必执行
evutil\u ascii\struct


多亏了@Grzegorz Szpetkowski提供的有用提示,我创建了以下工作正常的例程。之所以使用“kv=kv->next.tqe_next”是因为struct evkeyval定义中的“TAILQ_条目(evkeyval)next”

static void http_request_done(struct evhttp_request *req, void *ctx) {
    struct evkeyvalq *header = evhttp_request_get_input_headers(req);
    struct evkeyval* kv = header->tqh_first;
    while (kv) {
        printf("%s: %s\n", kv->key, kv->value);
        kv = kv->next.tqe_next;
    }
}

感谢@Grzegorz Szpetkowski的快速响应,我在/usr/local/include/event2中没有“event internal.h”。我可以将event internal.h复制到目录中,但犹豫了一下,因为这更像是一个乱码。@codingFun:这是一种“硬方法”,因此需要下载libevent源代码,因此需要手动编译。正如我所检查的,定义应该放在
http.c
中,适当的声明(原型)应该放在
include/event2/http.h
中(您可能在您的程序中使用它)。只要我不使用TAILQ\u宏,我的程序就可以编译,这有点奇怪。宏似乎只在内部头文件中。你怎么看?@codingFun:它是一个类似宏的内部函数,不打算公开给公共API(所以你的程序不会编译),本质上只是一个
for
循环,循环中有另一个
TAILQ\u FIRST
TAILQ\u END
TAILQ\u NEXT
f-l宏。
static void http_request_done(struct evhttp_request *req, void *ctx) {
    struct evkeyvalq *header = evhttp_request_get_input_headers(req);
    struct evkeyval* kv = header->tqh_first;
    while (kv) {
        printf("%s: %s\n", kv->key, kv->value);
        kv = kv->next.tqe_next;
    }
}