2014-02-26 39 views
0

例如,而不是這樣做:有什麼方法可以方便地爲Winsock send()生成一個HTTP頭,而不是手動連接一個字符串?

char * buf = "HTTP/1.0 200 OK\r\n..."; 
sendRet = send(ClientSocket, buf, strlen(buf), 0); 

事情是這樣的:

HttpHeader h; 
h.Version = "1.0"; 
h.Status = "200 OK"; 
h.ContentType = HTTP_CONTENT_TYPE_TEXT_XML; 
... 
sendRet = send(ClientSocket, h.ToString(), h.Length(), 0); 
+1

這是可用於C++ http://httplib.codeplex.com/如果有任何幫助 –

+0

或[WinHTTP](http://msdn.microsoft.com/en-us/library/windows/desktop/aa382925(v = vs.85).aspx)如果你想堅持本機窗口 – Mgetz

回答

0

你當然可以創建自己的HttpHeader來處理,但你最終還是不得不建立在HTTP它傳遞給send()之前手動頭,例如:

struct HttpHeader 
{ 
    char *Version; 
    char *Status; 
    char *ContentType; 
}; 

char* HttpHeaderToString(HttpHeader *hdr) 
{ 
    int len = strlen(hdr->Version) + strlen(hdr->Status) + 10; 
    if (strlen(hdr->ContentType) > 0) 
     len += (strlen(hdr->ContentType) + 16); 
    //... 

    char *str = (char*) malloc(len); 
    if (str != NULL) 
    {   
     sprintf(str, "HTTP/%s %s\r\n", hdr->Version, hdr->Status); 
     if (strlen(hdr->ContentType) > 0) 
     { 
      strcat(str, "Content-Type: "); 
      strcat(str, hdr->ContentType); 
      strcat(str, "\r\n"); 
     } 
     //... 
     strcat(str, "\r\n"); 
    } 
    return str; 
} 

HttpHeader h; 
h.Version = "1.0"; 
h.Status = "200 OK"; 
h.ContentType = HTTP_CONTENT_TYPE_TEXT_XML; 
... 
char *str = HttpHeaderToString(&h); 
if (str != NULL) 
{ 
    send(ClientSocket, str, strlen(str), 0); 
    free(str); 
} 

另一方面,TCP是一個字節流,因此您不必在單個呼叫中發送所有內容。您可以撥打send()多次,因爲你需要,如(檢查省略誤差爲簡潔起見):

void SendHttpHeader(HttpHeader *hdr) 
{ 
    send(ClientSocket, "HTTP/", 5, 0); 
    send(ClientSocket, hdr->Version, strlen(hdr->Version), 0); 
    send(ClientSocket, " ", 1, 0); 
    send(ClientSocket, hdr->Status, strlen(hdr->Status), 0); 
    send(ClientSocket, "\r\n", 2, 0); 
    if (strlen(hdr->ContentType) > 0) 
    { 
     send(ClientSocket, "Content-Type: ", 14, 0); 
     send(ClientSocket, hdr->ContentType, strlen(hdr->ContentType), 0); 
     send(ClientSocket, "\r\n", 2, 0); 
    } 
    //... 
    send(ClientSocket, "\r\n", 2, 0); 
} 

HttpHeader h; 
h.Version = "1.0"; 
h.Status = "200 OK"; 
h.ContentType = HTTP_CONTENT_TYPE_TEXT_XML; 
... 
SendHttpHeader(&h); 
+0

這是C++ - 問題被標記爲C.這就是爲什麼我把它作爲註釋 –

+1

OP的問題顯示了'h.ToString()'和'h.Length()',它不會在C中工作,因爲它不會支持類,或者記錄中的方法。將C++問題標記爲C或使用C++編譯器編寫C代碼並不罕見。如果C++沒有被實際使用,那麼將我的示例轉換爲C並不難。這並沒有改變我答案的核心要點。但是無論如何,我會用C重寫答案。 –

+0

你確定'h.ToString()'不能在C中工​​作 - 考慮http://codepad.org/CXa3O67c –

相關問題