Libevent HTTP client example

Views: 23562 | 4 Comments

This is a simple HTTP client written in C with libevent2, the client makes a HTTP request to a web server, and print out the response HTML text. Here’s the codes:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <evhttp.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/bufferevent.h>

void http_request_done(struct evhttp_request *req, void *arg){
    char buf[1024];
    int s = evbuffer_remove(req->input_buffer, &buf, sizeof(buf) - 1);
    buf[s] = '\0';
    printf("%s", buf);
    // terminate event_base_dispatch()
    event_base_loopbreak((struct event_base *)arg);

int main(int argc, char **argv){
    struct event_base *base;
    struct evhttp_connection *conn;
    struct evhttp_request *req;

    base = event_base_new();
    conn = evhttp_connection_base_new(base, NULL, "", 8080);
    req = evhttp_request_new(http_request_done, base);

    evhttp_add_header(req->output_headers, "Host", "localhost");
    //evhttp_add_header(req->output_headers, "Connection", "close");

    evhttp_make_request(conn, req, EVHTTP_REQ_GET, "/index.php?id=1");
    evhttp_connection_set_timeout(req->evcon, 600);

    return 0;
Posted by ideawu at 2013-09-11 21:55:59 Tags:

4 Responses to "Libevent HTTP client example"

  • Thanks for the quick idea, strangely enough, in the function http_request_done, req->evcon is also null, it always gives me segmentation fault when I try to call evhttp_connection_free() on it.
    Debugger also confirms req->evcon is null. Reply
    @jin: You can transmit connection reference through void *arg. For exammple you can create structure with connection, base and everything you need and use it Reply
  • Thanks for the simple but useful example.

    I need to send a few HTTP requests, after each HTTP transaction, I would like to close the TCP connection. In call back function http_request_done, I don’t have access to "conn" object to call evhttp_connection_free() on. Any ideas? Reply
    @jin: Hi, you can access to "conn" object by req->evcon. Reply

Leave a Comment