简体   繁体   中英

making http request with libevent

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM