When making http request with libevent, how can I get the length of content in response buffer? I know that evbuffer_remove()
can get data from buffer, but I want to know the length of the buffer.
evbuffer_get_length()
will tell you how many bytes are in the buffer and evbuffer_remove()
will return the number of bytes copied from the buffer. So you can do something like:
input = bufferevent_get_input(bev);
bytes_received = evbuffer_get_length(input);
/* Note calloc in case we copy less data than we have space allocated. */
data = calloc(bytes_received+1, sizeof(char));
bytes_copied = evbuffer_remove(input, data, bytes_received);
Otherwise, if you want to know how long the full HTTP response is, as Joachim Pileborg states, the headers will tell you how long the content is although this may not always be reliable. If you cannot rely on the server always giving an accurate content-length header, what you may have to do is keep reading, part-by-part, until you find the end of the HTTP response and for that I can highly recommend this library:
https://github.com/joyent/http-parser
It integrates with Libevent very well and very easily. In fact, I use this library to solve exactly this problem of determining the end of HTTP responses.