vc++ curl取得网页html文件内容的方法

首先就是一个回调函数

static size_t getResponseString(void *ptr, size_t size, size_t nmemb, void *userdata)
{//参数userdata是存放数据的指针 其他三个获取内容
std::string *version = (std::string*)userdata;
version->append((char*)ptr, size * nmemb);

return (size * nmemb);
}

然后就是一个curl 请求 

curl_global_init(CURL_GLOBAL_WIN32); 
CURL *easy_handle = curl_easy_init(); 
curl_httppost *post = NULL; curl_httppost *last = NULL; 
curl_formadd(&post, &last, CURLFORM_COPYNAME, "school_id", CURLFORM_COPYCONTENTS, IntToCString(pMain->m_nSchoolID), CURLFORM_END); 
curl_formadd(&post, &last, CURLFORM_COPYNAME, "exam_id", CURLFORM_COPYCONTENTS, IntToCString(pExam->m_nExamID), CURLFORM_END); 
curl_formadd(&post, &last, CURLFORM_COPYNAME, "key", CURLFORM_COPYCONTENTS, pMain->m_sDataKey, CURLFORM_END); 
curl_easy_setopt(easy_handle, CURLOPT_URL, "http://www.xx.com/nn/" + pMain->m_sCustomerCode + "/client/school-sheet-upload" ); 
std::string szbuffer; 
curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, getResponseString); 
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, &szbuffer); //curl_easy_setopt(easy_handle, CURLOPT_HTTPGET, post); curl_easy_setopt(easy_handle, CURLOPT_HTTPPOST, post); 
int nResult = curl_easy_perform(easy_handle); 
long http_code = 0; curl_easy_getinfo (easy_handle, CURLINFO_RESPONSE_CODE, &http_code); 
curl_formfree(post); 
curl_easy_cleanup(easy_handle); 
curl_global_cleanup(); 
CString strText = szbuffer.c_str(); 
strText = Utf_8ToUnicode(strText.GetBuffer(0)); 
//WriteLog(strText,"res.html"); 
if (strText == "1") {
 ( (CButton*)GetDlgItem(IDC_CHECK_SCHOOL_SHEET_UPLOAD))->SetCheck(TRUE); 
} 
else if ( strText == "0" ) { 
( (CButton*)GetDlgItem(IDC_CHECK_SCHOOL_SHEET_UPLOAD))->SetCheck(FALSE); 
}

Leave a Reply