2015-10-25 27 views
1

我需要下載一個html頁面塊。我建立了一個GET任務,可以下載一定範圍的數據。但我以重複的方式做這件事是不成功的。 基本上我必須reciver第一個0-99字節,然後100-199等等... 另外,我會很感激知道如何知道接收文件的確切大小事先使用C或C++代碼。 以下是我的代碼。 我已經免除了連接到套接字等,因爲它已經成功完成。我範圍在http下載

int c=0,s=0; 
while(1) 
{ 
    get = build_get_query(host, page,s); 
    c+=1; 
    fprintf(stderr, "Query is:\n<<START>>\n%s<<END>>\n", get); 
    //Send the query to the server 
    int sent = 0; 
    cout<<"sending "<<c<<endl; 
    while(sent < strlen(get)) 
    { 
     tmpres = send(sock, get+sent, strlen(get)-sent, 0); 
     if(tmpres == -1) 
     { 
      perror("Can't send query"); 
      exit(1); 
     } 
     sent += tmpres; 
    } 
    //now it is time to receive the page 
    memset(buf, 0, sizeof(buf)); 
    int htmlstart = 0; 
    char * htmlcontent; 
    cout<< "reciving "<<c<<endl; 
    while((tmpres = recv(sock, buf, BUFSIZ, 0)) > 0) 
    { 
     if(htmlstart == 0) 
     { 
      /* Under certain conditions this will not work. 
      * If the \r\n\r\n part is splitted into two messages 
      * it will fail to detect the beginning of HTML content 
      */ 
      htmlcontent = strstr(buf, "\r\n\r\n"); 
      if(htmlcontent != NULL) 
      { 
       htmlstart = 1; 
       htmlcontent += 4; 
      } 
     } 
     else 
     { 
      htmlcontent = buf; 
     } 
     if(htmlstart) 
     { 
      fprintf(stdout, htmlcontent); 
     } 

     memset(buf, 0, tmpres); 
    } 
    if(tmpres < 0) 
    { 
     perror("Error receiving data"); 
    } 
    s+=100; 
    if(c==5) 
     break; 
} 


char *build_get_query(char *host, char *page,int i) 
{ 
char *query; 
char *getpage = page; 

int j=i+99; 
char tpl[100] = "GET /%s HTTP/1.1\r\nHost: %s\r\nRange: bytes=%d-%d\r\nUser- Agent: %s\r\n\r\n"; 

if(getpage[0] == '/') 
{ 
    getpage = getpage + 1; 
    fprintf(stderr,"Removing leading \"/\", converting %s to %s\n", page, getpage); 
} 

query = (char  *)malloc(strlen(host)+strlen(getpage)+8+strlen(USERAGENT)+strlen(tpl)-5); 
sprintf(query, tpl, getpage, host, i , j, USERAGENT); 
return query; 
} 
+0

總大小是HTTP頭IIRC的最後部分。 –

回答

2

另外將不勝感激知道如何TOH知道接收文件預先用C或C++代碼的精確大小。

如果服務器支持的範圍內請求到特定的資源(其不能保證),則答案將是這樣的:

HTTP/1.1 206 partial content 
Content-Range: bytes 100-199/12345 

這意味着響應將包含100個字節.. 199並且內容的總大小是12345字節。

這裏有很多關於解析HTTP頭的問題,所以我不會詳細討論如何專門使用C/C++從頭中提取這些數據。

請注意,您正在執行HTTP/1.1請求,因此必須處理可能的分塊響應和隱式保持活動狀態。我真的建議使用現有的HTTP庫,而不是全部手工完成,並做錯了。如果您真的想自己實施,請致電the specification of HTTP

+0

你可以告訴我更多關於HTTP庫嗎? 關於如何從頭中提取這些數據,因爲我真的需要接收內容的總大小。 –

+0

@ridhikumari:它很難[使用搜索引擎](https://www.google.com/search?q=http+libraries+c%2B%2B),它可以快速爲您提供[許多HTTP庫] (http://curl.haxx.se/libcurl/competitors.html)? –

+0

感謝您的幫助! :) –