Download the C ++ code of an object through HTTP and compile and run it.

Source: Internet
Author: User
First create a website on the local machine, enable it, and then you can test it. Problem: You need to select a non-sustainable connection in the HTTP request header. If you do not write this row while Recv () will keep waiting for the input. (Personal understanding, no information found, do not know if it is correct) // httpclient. hfile # ifndef httpclient_h _ # define httpclient_h _ # include <string> # include <Winsock. h> # include <iostream> # include <fstream> # pragma comment (Lib, "ws2_32.lib") // # define tempdirectory "C: \" using namespace STD; class httpclient {public: httpclient (void );~ Httpclient (void); bool httpclient: downloadfile (socket parmsock, string servername, string sourcepath, string filename, string localdirectory, string port);}; # endif // httpclient. CPP file # include "httpclient. H "httpclient: httpclient (void) {} httpclient ::~ Httpclient (void) {}// for example servername = "127.0.0.1" or "localhost" // sourcepath = "/ABC/" // filename = "config. XML "// localdirectory =" C: \ "bool httpclient: downloadfile (socket parmsock, string servername, string sourcepath, string filename, string localdirectory, string port) {ofstream fout; string newfile = localdirectory + filename; // identifies the Chinese path and file name STD: locale: Global (STD: locale (""); fout. open (Newfile. c_str (), ios_base: Binary); If (! Fout. is_open () {cout <"Open newfile error! "<Endl;} Char szbuffer [1024]; // convert'' in the directory and file name to "% 20" // sourcepathint NPOs = sourcepath. find (""); While (NPOs + 1) {NPOs = sourcepath. find (""); If (NPOs =-1) break; sourcepath. replace (NPOs, strlen (""), "% 20");} // filenamenpos = filename. find (""); While (NPOs + 1) {NPOs = filename. find (""); If (NPOs =-1) break; filename. replace (NPOs, strlen (""), "% 20");} string requestfile = sourcepath + filename; //////////////////////////////////////// /////////////// // format the HTTP header // sprintf (szbuffer, "Get % s HTTP/1.1 \ r \ n", requestfile. c_str (); // strcat (szbuffer, "Host:"); strcat (szbuffer, servername. c_str (); strcat (szbuffer, ":"); strcat (szbuffer, port. c_str (); strcat (szbuffer, "\ r \ n"); // The third line // strcat (szbuffer, "accept :*/*"); /* strcat (szbuffer, "\ r \ n "); //// // The fourth line (optional) strcat (szbuffer, "User-Agent: generaldownloadapplication"); strcat (szbuffer, "\ r \ n"); * // the fifth line of the non-persistent connection strcat (szbuffer, "connection: close "); strcat (szbuffer," \ r \ n "); // The last line of strcat (szbuffer," \ r \ n "); int nret = Send (parmsock, szbuffer, strlen (szbuffer), 0); If (nret = socket_error) {cout <"Send () error" <Endl; closesocket (parmsock); Return false ;} /// receive the file contents and print to stdout //////////////////////////// /// // HTTP header, the size should not exceed 1024 bytes, only processing is performed at the first reception ///////////////////////////////// /// // nret = Recv (parmsock, szbuffer, sizeof (szbuffer), 0); If (nret = socket_error) {cout <"Recv () error" <Endl; closesocket (parmsock); fout. close (); wsacleanup (); Return false ;} //////////////////////////////////////// //////////////
// Determine whether the file exists
        std::string strBuffer = szBuffer; 
        std::string firstString = strBuffer.substr(0,strBuffer.find("\r\n")); 
        int File_Exist = firstString.find("200"); 
        if(File_Exist == -1) 
        {  
              cout<<"File not found in the web."<<endl;  
              return false; 
         }
// Get the start position of the file content int I = 0; while (1) {If (szbuffer [I] = '\ R ') & (szbuffer [I + 1] = '\ n') & (szbuffer [I + 2] =' \ R ') & (szbuffer [I + 3] = '\ n') {break;} I ++;} // start int filebegin = I + 4; //////////////////////////////////////// /// // for (I = filebegin; I <nret; I ++) {fout. write (& szbuffer [I], sizeof (szbuffer [I]);}/* Static int COUNT = 0; count + = nret-filebegin ;*/
While (1) {// wait to receive, nret = numberofbytesreceived nret = Recv (parmsock, szbuffer, sizeof (szbuffer), 0); If (nret = socket_error) {cout <"Recv () error" <Endl; closesocket (parmsock); fout. close (); wsacleanup (); Return false ;} //////////////////////////////////////// /// // cout <"\ nrecv () returned "<nret <" bytes "<Endl; If (nret = 0) break; // write to stdoutcount + = NRE T; fout. write (szbuffer, nret);} closesocket (parmsock); fout. close (); wsacleanup (); Return true;} // main. CPP file # include "httpclient. H "// # include <iostream> int main () {httpclient m; // M. downloadfile ("localhost", "/ABC/", "config. XML "," d :\\ "); STD: String url =" http: // localhost/water lilies.jpg "; STD: String localdirectory =" D: \ China \ "; STD: string port =" 5550 "; // cout <m. contentlengthint <Endl; // cout <m. R Angeint <Endl; //////////////////////////////////////// /// // STD:: String removeprotocol; STD: String servername; STD: String sourcepath; STD: String filename; int ret; ret = URL. find ("http: //"); If (Ret! =-1) {removeprotocol = URL. substr (strlen ("http: //");} else {removeprotocol = URL;}/* ret = URL. find ("https: //"); If (Ret! =-1) {removeprotocol = URL. substr (strlen ("https: //");} else {removeprotocol = URL;} */ret = removeprotocol. find_first_of ('/'); servername = removeprotocol. substr (0, RET); int net = removeprotocol. find_last_of ('/'); sourcepath = removeprotocol. substr (Ret, net-ret + 1); filename = removeprotocol. substr (net + 1 ); //////////////////////////////////////// /// // wsadata; int nret; // ini Tialize Winsock. dll // nret = wsastartup (0x101, & wsadata); If (nret) {wsacleanup (); Return false;} If (wsadata. wversion! = 0x101) {wsacleanup (); Return false;} in_addr iahost; lphostent lphostentry; iahost. s_addr = inet_addr (servername. c_str (); If (iahost. s_addr = inaddr_none) {// wasn' t an IP address string, assume it is a name lphostentry = gethostbyname (servername. c_str ();} else {// It was a valid IP address string lphostentry = gethostbyaddr (const char *) & iahost, sizeof (struct in_addr), af_inet );} if (lphostentry = NULL) {cout <"gethostbyname () error" <Endl; return false ;} /// create a TCP/IP stream socket // socket parmsock; parmsock = socket (af_inet, sock_stream, ipproto_tcp); If (parmsock = invalid_socket) {cout <"socket () error" <Endl; return false;} // find the port number for the HTTP service on TCP // lpservent; sockaddr_in saserver; lpservent = getservbyname ("HTTP", "TCP"); If (lpservent = NULL) saserver. sin_port = htons (80); elsesaserver. sin_port = lpservent-> s_port; // fill in the rest of the server address structure // saserver. sin_family = af_inet; saserver. sin_addr = * (lpin_addr) * lphostentry-> h_addr_list); // connect the socket // nret = connect (parmsock, (lpsockaddr) & saserver, sizeof (sockaddr_in); If (nret = socket_error) {cout <"Connect () error" <Endl; closesocket (parmsock); Return false ;} //////////////////////////////////////// /// // M. downloadfile (parmsock, servername, sourcepath, filename, localdirectory, Port); System ("pause"); Return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.