Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Retrieving a file through http

Posted on 1997-10-28
2
Medium Priority
?
282 Views
Last Modified: 2013-11-20
I'm trying to retrieve a file off a web site using MFC,
can you explain how to open a connection and retrieve a
specific file (in this case it's a JPEG graphics file).
0
Comment
Question by:nicholso
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 2

Accepted Solution

by:
wpinto earned 400 total points
ID: 1309006
Hi nicholso,

Please look at the code below, it does what you want it to do. The argument to the function should a URL eg: http://www...
Note the http:// is necessary.

This code has been taken from the Tear example which comes with MFC & has been slightly modified to suit your needs.

This code is self-explanatory, please let me know if you face any problems while implementing it

You could also have a look at the Tear example

Hope this helps

Wilfred

------------------------------------------------------------------------------------------

BOOL GetFileFromNet(CString pszURL)
{
      BOOL bRetCode = TRUE;

      CHttpConnection* pServer = NULL;
      CHttpFile* pFile = NULL;
      CString strNewFileName("");

      try
      {
            // check to see if this is a reasonable URL

            CString strServerName;
            CString strObject;
            INTERNET_PORT nPort;
            DWORD dwServiceType;

            if (!AfxParseURL(pszURL, dwServiceType, strServerName, strObject, nPort) ||
                  dwServiceType != INTERNET_SERVICE_HTTP)
            {
                  cerr << _T("Error: can only use URLs beginning with http://") << endl;
                  return FALSE;
            }

            if (bProgressMode)
            {
                  cerr << _T("Opening Internet...");
                  VERIFY(session.EnableStatusCallback(TRUE));
            }

            // Retrieve the name of the file
            int index = strObject.ReverseFind('/');
            strNewFileName = strObject.Mid(index+1);

            // connect
            pServer = session.GetHttpConnection(strServerName, nPort);

            // request for file
            pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,
                  strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
            pFile->AddRequestHeaders(szHeaders);
            pFile->SendRequest();

            DWORD dwRet;
            pFile->QueryInfoStatusCode(dwRet);

            // if access was denied, prompt the user for the password

            if (dwRet == HTTP_STATUS_DENIED)
            {
                  DWORD dwPrompt;
                  dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD,
                        FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL);

                  // if the user cancelled the dialog, bail out

                  if (dwPrompt != ERROR_INTERNET_FORCE_RETRY)
                  {
                        cerr << _T("Access denied: Invalid password\n");
                        return FALSE;
                  }

                  pFile->SendRequest();
                  pFile->QueryInfoStatusCode(dwRet);
            }

            CString strNewLocation;
            pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation);

            // were we redirected?
            // these response status codes come from WININET.H

            if (dwRet == HTTP_STATUS_MOVED ||
                  dwRet == HTTP_STATUS_REDIRECT ||
                  dwRet == HTTP_STATUS_REDIRECT_METHOD)
            {
                  CString strNewLocation;
                  pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation);

                  int nPlace = strNewLocation.Find(_T("Location: "));
                  if (nPlace == -1)
                  {
                        cerr << _T("Error: Site redirects with no new location") << endl;
                        return FALSE;
                  }

                  strNewLocation = strNewLocation.Mid(nPlace + 10);
                  nPlace = strNewLocation.Find('\n');
                  if (nPlace > 0)
                        strNewLocation = strNewLocation.Left(nPlace);

                  // close up the redirected site

                  pFile->Close();
                  delete pFile;
                  pServer->Close();

                  if (bProgressMode)
                  {
                        cerr << _T("Caution: redirected to ");
                        cerr << (LPCTSTR) strNewLocation << endl;
                  }

                  // figure out what the old place was
                  if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort))
                  {
                        cerr << _T("Error: the redirected URL could not be parsed.") << endl;
                        return FALSE;
                  }

                  if (dwServiceType != INTERNET_SERVICE_HTTP)
                  {
                        cerr << _T("Error: the redirected URL does not reference a HTTP resource.") << endl;
                        return FALSE;
                  }

                  // try again at the new location
                  pServer = session.GetHttpConnection(strServerName, nPort);
                  pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,
                        strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags);
                  pFile->AddRequestHeaders(szHeaders);
                  pFile->SendRequest();

                  pFile->QueryInfoStatusCode(dwRet);
                  if (dwRet != HTTP_STATUS_OK)
                  {
                        cerr << _T("Error: Got status code ") << dwRet << endl;
                        return FALSE;
                  }
            }

            cerr << _T("Status Code is ") << dwRet << endl;

            if (!strNewFileName.IsEmpty())
            {
                  // create new file
                  CFile pNewFile;
                  pNewFile.Open("c:\\temp\\"+ strNewFileName, CFile::modeCreate | CFile::modeWrite);

                  long nRead=0;
                  char sz[1024];

                  nRead = pFile->Read(sz, 1023);
                  while (nRead > 0)
                  {
                        pNewFile.Write(sz, nRead);
                        nRead = pFile->Read(sz, 1023);
                  }

                  pNewFile.Close();
            }

            pFile->Close();
            pServer->Close();
      }
      catch (CInternetException* pEx)
      {
            // catch errors from WinINet

            TCHAR szErr[1024];
            pEx->GetErrorMessage(szErr, 1024);

            cerr << _T("Error: (") << pEx->m_dwError << _T(") ");
            cerr << szErr << endl;

            bRetCode = FALSE;
            pEx->Delete();
      }

      if (pFile != NULL)
            delete pFile;
      if (pServer != NULL)
            delete pServer;
      session.Close();

      return bRetCode;
}

0
 
LVL 2

Expert Comment

by:wpinto
ID: 1309007
Hi nicholso,

Couple of things I forgot

Please add the following statement just after the try statement
ie.
try
{
      CInternetSession session(_T("Test app"));
      ...

Also remove the following code (in 2 places)
if (bProgressMode)
{
 ...
}

Hope this helps

Wilfred
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Load and Save to file, Document-View interaction inside the SDI. Continuing from the second article about sudoku.   Open the project in visual studio. From the class view select CSudokuDoc and double click to open the header …
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…

660 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question