A simple way of downloading files from the web server.

zhaozj2021-02-11  274

You can implement one function, first include the header file AFXINET.H

The following is the required code.

Bool cdownloaddlg :: GetFromweb (lpstr purl, lpstr saveasfilepath) {cinternetSession session; // session time object)

ChttpConnection * pserver = null; // Point to the server address (URL)

Chttpfile * phttpfile = null; // http file pointer

CString strservername; // server name

CSTRING STROBJECT; / / Query Object Name (HTTP file)

Internet_port nport; // port

DWORD DWSERVICEPE; // Service Type

DWORD DWHTTPREQUESTFLAGS = // Request Sign

// Internet_flag_existing_connect;

Internet_flag_no_auto_redirect;

Const tchar szheaders [] = _ t ("accept: text / * / r / nuser-agent: httpclient / r / n");

BOOL OK = AFXPARSEURL (// lexical analysis

PURL, // is analyzed URL string

DWSERVICETYPE, // Service type, FTP, HTTP, etc.

STRSERVERNAME, // server name

Strobject, // URL query object

NPORT); // URL specified port, may be empty

OK = OK && // This example only considers the HTTP protocol

(dWServiceType ==

Internet_Service_HTTP);

IF (! ok)

{AFXMessageBox ("URL error"); // report error

Return False;

}

PServer = session.gethttpConnection (strserverName, nport); // Get server name

PHTTPFILE = PServer-> OpenRequest (chttpConnection :: http_verb_get, strobject, null, 1, null, null, dwhttpRequestflags);

/ / Send a request to the server, establish an HTTP connection,

/ / Establish the HTTP file pointer on this unit

PHTTPFILE-> AddRequestHeaders (Szheaders);

Phttpfile-> sendrequest (); // Send request

CSTDIOFILE F; // Output file object

IF (! f.Open (// Open Output File

SaveasfilePath, CFile :: ModeCreate | CFILE :: Modewrite | CFILE :: Typebinary))

{MessageBox ("Unable to open file");

Return False;

}

// Save the search result to the file below

TCHAR SZBUF [1024]; // Cache INT length = 0; long a = phttpfile-> getLength (); while (length = phttpfile-> read (szbuf, 1023)))

F.Write (SZBUF, Length);

f.close (); // after work

PHTTPFILE -> Close ();

PSERVER -> Close ();

IF (PHTTPFILE! = null) delete phttpfile;

IF (PServer! = null) delete PServer;

Session.close (); Return True;

}

转载请注明原文地址:https://www.9cbs.com/read-4271.html

New Post(0)