一个小例子:
class libcurlParser : public QThread
{
Q_OBJECT
public:
static size_t process(void* buffer,size_t size,size_t n,void *user);
QString html;
public:
libcurlParser(QObject *parent= 0);
~libcurlParser();
public:
void execute(const QString& url);
public slots:
void finishSlot();
void timeOut();
signals:
void finish();
protected:
void run();
private:
CURL* curl;
};
size_t libcurlParser::process(void* buffer,size_t size,size_t n,void *user)
{
libcurlParser* parser = (libcurlParser*)user;
parser->html += (char*)buffer;
return size*n;
}
libcurlParser::libcurlParser(QObject *parent)
: QThread(parent)
{
connect(this,SIGNAL(finish()),this,SLOT(finishSlot()));
curl = curl_easy_init();
}
libcurlParser::~libcurlParser()
{
curl_easy_cleanup(curl);
}
void libcurlParser::execute(const QString& url)
{
html.clear();
curl_easy_setopt(curl,CURLOPT_URL,url.toAscii().data());
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,&process);
curl_easy_setopt(curl,CURLOPT_WRITEDATA,this);
start();
}
void libcurlParser::run()
{
CURLcode code = curl_easy_perform(curl);
std::cout<<"exe:"<<"code"<<std::endl;
emit finish();
//std::cout<<curl_easy_strerror(code)<<std::endl;
//QTimer::singleShot(0, this, SLOT(timeOut()));
//exec();
}
void libcurlParser::finishSlot()
{
std::cout<<"finishSlot()"<<std::endl;
QFile file("htm.htm");
file.open(QIODevice::WriteOnly);
file.write(html.toLatin1());
file.close();
}
void libcurlParser::timeOut()
{
emit finish();
}