2013-01-04 58 views
0

我試圖在包含授權標題的c編程中實現一個http(GET請求),但問題是我無法獲得(200好的),我只有一個會話通信(服務器答覆需要401授權)但不超過。在c執行http授權標題

**while(1){ 

    strcpy(buffer,"GET /mywebsite/login.html/ HTTP1.1 \n\n"); 
    strcat(buffer,"Host: localhost\n\n"); 
    strcat(buffer,"Connection: keep-alive\n\n"); 
    strcat(buffer,"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11\n\n"); 
    strcat(buffer,"Accept: text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8\n\n"); 
    strcat(buffer,"Accept-Encoding: gzip,deflate,sdch\n\n"); 
    strcat(buffer,"Accept-Language: en-US,en;q=0.8\n\n"); 
    strcat(buffer,"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n\n"); 
    status = send(sock, buffer, strlen(buffer), 0); 
    if(status == -1) { 
     printf("Error in send(). Error code: %d\n", WSAGetLastError()); 
     continue; 
    } 
    buffer[0]='\0'; 
    //The receiving functions 
    status = recv(sock, buffer, BUFFER_SIZE, 0); 
    if (status == -1) { 
     printf("Error in recv(). Error code: %d\n", WSAGetLastError()); 
     continue; 
    } 
    buffer[status] = '\0'; 
    printf("The message received is: "); 
    printf("%s\n\n", buffer); 

    strcpy(buffer,"GET /mywebsite/login.html/ HTTP1.1\n\n"); 
    strcat(buffer,"Host: localhost\n\n"); 
    strcat(buffer,"Authorization: Basic QWRtaW46MTIzNA== \n\n"); 
    strcat(buffer,"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11\n\n"); 
    strcat(buffer,"Accept: text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8\n\n"); 
    strcat(buffer,"Accept-Encoding: gzip,deflate,sdch\n\n"); 
    strcat(buffer,"Accept-Language: en-US,en;q=0.8\n\n"); 
    strcat(buffer,"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n\n"); 
    strcat(buffer,"Connection: keep-alive\n\n"); 
    status = send(sock, buffer, strlen(buffer), 0); 
    if(status == -1) { 
     printf("Error in send(). Error code: %d\n", WSAGetLastError()); 
     continue; 
    } 
    buffer[0]='\0'; 
    //The receiving functions 
    status = recv(sock, buffer, BUFFER_SIZE, 0); 
    if (status == -1) { 
     printf("Error in recv(). Error code: %d\n", WSAGetLastError()); 
     continue; 
    } 
    buffer[status] = '\0'; 
    printf("%s\n\n", buffer); 
    buffer[0]='\0'; 

}** 

第一首部發送成功,但接下來的頭所在服務器保持無爲(無回覆) 這裏討一點幫助我沒有的問題是什麼任何線索... :(

+0

您應該確保您可以手動執行請求(即手動寫出HTTP請求)。然後將它們與您的代碼生成的文本進行比較。 –

+0

如果可行,請嘗試使用像Fiddler這樣的工具來查看流量。 – Pete

回答

2

有一些明顯的問題:

  • 頭應爲 「\ r \ n」,而不是 「\ n \ n」,最後用 「\ r \ n \ r \ n」 結尾的分隔
  • send and recv should b e在errno上重試== EINTR
  • send可能發送的字節數少於請求的字節數,因此應該在循環中使用它以確保傳輸所有數據。
+0

而且代碼應確保服務器確實保持連接正常運行。 – Codo

+0

非常感謝你們,因爲那個節目我做了噩夢,看到(200好)真的很高興,所以謝謝你。 – chard