VC中使用CInternetSession抓取網(wǎng)頁內(nèi)容

字號:

在 VC 中用 WinInet 的 CInternetSession::OpenURL(url),得到一個 CFile,讀取其中的內(nèi)容即可,詳細(xì)代碼如下
    #include
    #include
    int main(int argc, char* argv[])
    {
    CInternetSession session("HttpClient");
    char * url = " http://www.imobile.com.cn/simcard.php?simcard=1392658";
    CHttpFile* pfile = (CHttpFile *)session.OpenURL(url);
    DWORD dwStatusCode;
    pfile -> QueryInfoStatusCode(dwStatusCode);
    if(dwStatusCode == HTTP_STATUS_OK)
    {
    CString content;
    CString data;
    while (pfile -> ReadString(data))
    {
    content += data + "rn";
    }
    content.TrimRight();
    printf(" %sn " ,(LPCTSTR)content);
    }
    pfile -> Close();
    delete pfile;
    session.Close();
    return  0 ;
    }
    #include
    #include
    int main(int argc, char* argv[])
    {
    CInternetSession session("HttpClient");
    char * url = " http://www.imobile.com.cn/simcard.php?simcard=1392658";
    CHttpFile* pfile = (CHttpFile *)session.OpenURL(url);
    DWORD dwStatusCode;
    pfile -> QueryInfoStatusCode(dwStatusCode);
    if(dwStatusCode == HTTP_STATUS_OK)
    {
    CString content;
    CString data;
    while (pfile -> ReadString(data))
    {
    content += data + "rn";
    }
    content.TrimRight();
    printf(" %sn " ,(LPCTSTR)content);
    }
    pfile -> Close();
    delete pfile;
    session.Close();
    return  0 ;
    }
    其他如不從緩存中讀取內(nèi)容及如何使用代理連接現(xiàn)在就不說了,可以參考下面的鏈接,或者下次補(bǔ)上。另外不妨看看 Java 是如何讀取 URL 內(nèi)容的,更簡單
    GetMethod httpMethod = new GetMethod("http://unmi.blogcn.com");
    int statusCode = new HttpClient().executeMethod(httpMethod);
    if(statusCode == HttpStatus.SC_OK)
    {
    System.out.println(httpMethod.getResponseBodyAsString());
    }
    httpMethod.releaseConnection();
    GetMethod httpMethod = new GetMethod("http://unmi.blogcn.com");
    int statusCode = new HttpClient().executeMethod(httpMethod);
    if(statusCode == HttpStatus.SC_OK)
    {
    System.out.println(httpMethod.getResponseBodyAsString());
    }
    httpMethod.releaseConnection();
    內(nèi)容取過來之后,總是希望從中揀出需要的數(shù)據(jù),可惜 VC6 中沒有自己的正則表達(dá)式庫,所以下一步要學(xué)用 boost 的正則表達(dá)式庫。