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

时间:2014-07-19 15:41:10

标签: 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);

我知道我可以获得如下所示的单个标题,但如何获取所有标题?

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"));
}

感谢。

2 个答案:

答案 0 :(得分:3)

虽然我之前没有使用过libevent库的任何经验,但我很清楚API并没有提供这样的功能(请参阅API参考)。但是,您可以使用TAILQ_FOREACH内部宏编写自己的方法,该宏在event-internal.h中定义。 evhttp_find_header的定义相当简单:

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);
}

您只需从evutil_ascii_strcasecmp结构(在header->key中定义)获取header->valueevkeyval条目,而不是include/event2/keyvalq_struct.h {/ p>}。

/*
 * Key-Value pairs.  Can be used for HTTP headers but also for
 * query argument parsing.
 */
struct evkeyval {
    TAILQ_ENTRY(evkeyval) next;

    char *key;
    char *value;
};

答案 1 :(得分:2)

感谢来自@Grzegorz Szpetkowski的有用提示,我创建了以下例程,该工作正常。使用“kv = kv-> next.tqe_next”的原因是因为struct evkeyval定义中的“TAILQ_ENTRY(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;
    }
}