2007년 4월 10일 화요일

CInternetSession, CHttpConnection, CHttpFile 예제

#include "stdafx.h"
#include "main.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

using namespace std;

void ParseCmdLine(int argc, TCHAR* argv[], TCHAR* envp[]);
void Say(CString status);

int TMainApp(int argc, TCHAR* argv[], TCHAR* envp[]) {

    Say("Parsing command line...");
    ParseCmdLine(argc, argv, envp);

    Say("Allocating variables...");
    CString m_sURL = "http://www.digital.go.kr/rss/fc_textxml.jsp?row=120&col=61®ion=7&locationcode=4111573000";
    CInternetSession m_Session;
    CHttpConnection* m_pHttpConnection=NULL;
    CHttpFile* m_pHttpFile = NULL;

    Say("Connecting...");
    try {
        m_pHttpConnection = m_Session.GetHttpConnection(m_sURL,(INTERNET_PORT)80, NULL, NULL);
        if( m_pHttpConnection == NULL )
            throw CString("Http connection failed");

        m_pHttpFile = (CHttpFile*)m_Session.OpenURL(m_sURL);
    
        if( !m_pHttpFile ) {
            m_pHttpFile->Close();
            delete m_pHttpFile;
            throw CString("HttpFile connection failed");
        }
    }
    catch ( CInternetException *pEx ) {
        if ( m_pHttpFile) {
            m_pHttpFile->Close();
            delete m_pHttpFile;
        }
        if ( m_pHttpConnection ) {
            m_pHttpConnection->Close();
            delete m_pHttpConnection;
        }
        TCHAR lpszErrorMessage[255];
        pEx->GetErrorMessage(lpszErrorMessage, 255);
        pEx->Delete();
        cout << lpszErrorMessage << endl;
        return 1;
    }
    catch (CString e) {
        cout << "Error : " << (LPCTSTR)e << endl;
        cout << "Program aborted..." << endl;
        return -1;
    }
    Say("Connection established.");

    Say("Listing file...");
    CString line;
    while ( m_pHttpFile->ReadString(line) != NULL ) {
        // line += "\r\n";
        wcout << (LPCTSTR)line << endl;
    }
    Say("Listing complete");

    Say("Shutdown process started");
    Say("Deleting m_pHttpFile...");
    if ( m_pHttpFile) {
        m_pHttpFile->Close();
        delete m_pHttpFile;
    }
    Say("Deleting m_pHttpConnection...");
    if ( m_pHttpConnection ) {
        m_pHttpConnection->Close();
        delete m_pHttpConnection;
    }

    return 0;
}

void ParseCmdLine(int argc, TCHAR* argv[], TCHAR* envp[]) {

//  if ( argc != 2 )
//      throw CString(L"Usage : inet.exe ip_address");

}

void Say(CString status) {
    cout << (LPCTSTR)status << endl;
}


댓글 없음: