curl

curl-7.21.7

#include <iostream>
#include <string.h>
#include "curl/curl.h"

using namespace std;
class CurlBuffer {
  public:
    char *buffer_ptr_;
    size_t buffer_size_;
    
    CurlBuffer() {
      buffer_ptr_ = new char[204800];
      buffer_size_ = 0;
    }   
    ~CurlBuffer() {
      delete buffer_ptr_;
    }   
};

size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *data) {
  CurlBuffer *buffer  = (CurlBuffer *)data;
  memcpy(buffer->buffer_ptr_+buffer->buffer_size_, ptr, size*nmemb);
  buffer->buffer_size_ += size*nmemb;
  buffer->buffer_ptr_[buffer->buffer_size_] = 0;
  return size*nmemb;
}

int main (int argc, char *argv[]) {
  CurlBuffer url_buffer_;
  CURLcode curl_code_ = curl_global_init(CURL_GLOBAL_ALL);

  if (curl_code_ != CURLE_OK) {    
     return 1;    
  }
  string url="http://www.baidu.com";

  url_buffer_.buffer_size_ = 0;
  CURLcode ret ;
  CURL *curl = curl_easy_init();

  if (curl) {
//    curl_easy_setopt(curl, CURLOPT_POST, 0);
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&url_buffer_);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 15000);
    struct curl_slist *slist=NULL;
    slist = curl_slist_append(slist, "user-id:221666396");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
    ret = curl_easy_perform(curl);  //这是个阻塞函数,等都下载完了才往下执行
  }
  long response_code = 0;
  ret = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  double download_size = 0;
  ret = curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &download_size);

  curl_easy_cleanup(curl);
  string json;
  if (response_code==200 && download_size>0)
    json = string(url_buffer_.buffer_ptr_, url_buffer_.buffer_size_);
  cout << "content:" << json;
 curl_global_cleanup();
}


 
展开阅读全文

没有更多推荐了,返回首页