1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
void downloadFile( string server, string file )
{
Socket client;
client.create();
client.connect(server, 80);
client.send("GET " + file + " HTTP/1.1\r\n");
client.send("Host: "+ server + "\r\n\r\n");
int len = 0;
char* response = new char[1024];
len = client.c_recv(response);
int endLines = 0;
for(;;)
{
char* point = (char*) memchr(response+endLines+1, '\r', len);
int pos = point-response;
endLines = pos;
if(response[pos+1] == '\n' && response[pos+2] == '\r' && response[pos+3] == '\n')
{
break;
}
}
char* htmp = new char[endLines];
memcpy(htmp, response, endLines);
string header(htmp);
delete [] htmp;
int found = header.find("Content-Length: ");
for(int n=found+15; n<=endLines; n++){
if(header[n] == '\n'){
header.erase(n,endLines);
header.erase(0,found+16);
break;
}
}
stringstream ss;
ss << header;
size_t fileSize;
ss >> fileSize;
size_t downloaded = 0;
char* wholeContent = new char [fileSize];
char* tmp = new char[len-endLines];
memcpy(tmp, response+endLines+4, len-endLines );
memcpy(wholeContent, tmp, len-endLines );
delete [] tmp;
downloaded += len-endLines+1;
while ( downloaded < fileSize )
{
memset(response, 0, 1024);
len = client.c_recv(response);
memcpy(wholeContent+downloaded+1, response, len);
downloaded+=len;
}
delete [] response;
ofstream nFile("image.png", std::ios::out | std::ios::binary | std::ios::ate );
nFile.write(wholeContent, fileSize);
nFile.close();
delete [] wholeContent;
}
]
|