发现一个比ghttp更好的HTTP库, 它不仅支持http,也支持https.
struct MemoryStruct {
char *data;
size_t size;
};
static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->data = realloc(mem->data, mem->size + realsize + 1);
if (mem->data) {
memcpy(&(mem->data[mem->size]), ptr, realsize);
mem->size += realsize;
mem->data[mem->size] = 0;
}
return realsize;
}
int load_net_file(const char *uri, long *httpCode, struct MemoryStruct *chunk)
{
CURL *curl = NULL;
CURLcode cret;
if(!uri || !chunk)
return -1;
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "Failed to init curl.");
return -1;
}
if(httpCode)
*httpCode = 0;
chunk->size = 0;
chunk->data = NULL;
curl_easy_setopt(curl, CURLOPT_URL, uri);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
/* NOTE: It must be set, otherwise it will crash when timeout */
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
#if 0
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
#endif
cret = curl_easy_perform(curl);
if(cret == CURLE_OK) {
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, httpCode);
curl_easy_cleanup(curl);
return 0;
}
/* Error case */
curl_easy_cleanup(curl);
if(cret == CURLE_URL_MALFORMAT) {
/* Handle it */
}
else if(cret == CURLE_OPERATION_TIMEDOUT) {
/* Handle it */
}
return -1;
}
具体资料请查阅: http://curl.haxx.se
阅读(4336) | 评论(0) | 转发(0) |