#include <STDIO.H>
#include <WINSOCK2.H>
#include <stdlib.h>
#pragma comment (lib,"ws2_32.lib")
#define BUFLENGHT 1024
#define NAME_LENGHT 50
char fname[NAME_LENGHT];
int delete_http_header(SOCKET s,char *strBuffer,int &body_lenght)
{ //返回当前文件主体的位置
int end_flag=0;//头结束
for (int break_flag=0;break_flag==0;)
{ //
//去除http响应头部
strset(strBuffer,'\0');
// iResult = recv(s,status,sizeof(status),0);
int iResult = recv(s,strBuffer,BUFLENGHT,0);
if (iResult<=0)
{
iResult=GetLastError();
break;
}
int code = atoi(&strBuffer[8]);
if (code == 404)
{
return -1;
}
for (int i=0;(i<BUFLENGHT)&&(break_flag==0);i++)
{
if (strBuffer[i]=='C')
{
if (strBuffer[i+9]=='e')
{
body_lenght=atoi(&strBuffer[i+15]);
}
}
if (end_flag==4)
{
return i;
}
if ((strBuffer[i]=='\r')|| (strBuffer[i]=='\n'))
{
end_flag++;
continue;
}
end_flag=0;
}
}
}
BOOL HttpClient(void)
{
WSADATA ws;
SOCKET s;
struct sockaddr_in addr;
int body_lenght=0;
int sum=0;
int iResult;
long lResult;
char strSubAddr[BUFLENGHT] = {0};
char strBuffer[BUFLENGHT] = {0};
iResult = WSAStartup( MAKEWORD(2,0),&ws);
if(SOCKET_ERROR == iResult)
{
// 连接失败
WSACleanup();
return FALSE;
}
s = socket(AF_INET,SOCK_STREAM,0);
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
HOSTENT *remot;
remot= gethostbyname("xiazai.xiazaiba.com");//获得域名的ip
if(remot==NULL)
{
DWORD er=GetLastError();
return -1;
}
in_addr pttr;
memcpy(&pttr,remot->h_addr_list[0],4);//复制域名转换得到的ip到新定义的地址变量中,这是不可或缺的,因为可读性好,且正确
char *ip=inet_ntoa(pttr); //将存储顺序修改为net
addr.sin_addr.s_addr = inet_addr(ip); // 填充ip地址
iResult=connect(s,(struct sockaddr *)
&addr, sizeof(addr));
// 连接成功
请求码///
char *request =
"GET /Soft/D/DocLibDownload_1.2.0_XiaZaiBa.zip HTTP/1.1 \r\n"
"Host:xiazai.xiazaiba.com \r\n"//必须包含host其他不一定了
"Accept: */* \r\n"
"pragma: no-cache \r\n"
"Cache-control: no-cache \r\n"
"Connect:Close \r\n"
"\r\n";
strcpy(strSubAddr, "GET /view/pic/2009515164715518.jpg HTTP/1.1 \r\n");
strcpy(fname, "DocLib.zip");
iResult = send(s, request,strlen(request),0);
if (iResult<=0)
{
iResult=GetLastError();
return -1;
}
// 下载文件
FILE *fp=fopen(fname,"wb+");
int n_body=delete_http_header(s,strBuffer,body_lenght);//删除协议头
if (n_body < 0)
{
return FALSE;
}
char str[BUFLENGHT] = {0};
memcpy((void*)str, (void*)&strBuffer[n_body], BUFLENGHT-n_body);
fwrite(&strBuffer[n_body],(BUFLENGHT-n_body),1,fp);
sum+=BUFLENGHT-n_body;
int percent=0;
for (int i=0;;i++)
{
if (sum>=body_lenght)
{
break;
}
memset(&strBuffer,0,sizeof(strBuffer));
if((iResult = recv(s,strBuffer,BUFLENGHT,0))<=0)
{
break;
}
if(fwrite(&strBuffer,iResult,1,fp)<=0)
{
break;
}
sum+=iResult;
if(percent != sum*100/body_lenght)
{
percent = sum*100/body_lenght;
printf("%%d 完成",percent);
}
}
fclose(fp);
WSACleanup();
return TRUE;
}