2013-07-02 22 views
-2

我試圖發送一個HTTP POST請求使用Code :: Blocks .c,但我不知道什麼是錯誤的消息,我搜索谷歌和所有教程教我做像我一樣,所以如果有人能幫助我,我要謝謝你,這裏是我的要求到現場::未能發送一個HTTP POST請求在C

sprintf(buffer, "POST /index.php HTTP/1.1\r\nContent-Lenght: %d\r\n", 7+strlen(action)+3+strlen(id)); 
strcat(buffer, "Host: www.testserv.com \r\n\r\n"); 
strcat(buffer, "action=");strcat(buffer, action); 
strcat(buffer, "&"); 
strcat(buffer, "id=");strcat(buffer, id); 

printf("Requisicao:\n%s\n\n", buffer); 

send(s, buffer, strlen(buffer), 0); 

的要求似乎是正確的,但她不工作的事錯誤?

----編輯--- 問題是:我的發佈請求不起作用,只有HTTP標頭被服務器解釋,但是形式itens的值沒有!

解釋站點: 該站點有一個index.php頁面和由index.php:send.php調用的第二個頁面。 索引頁有一個3 itens:2文本框(動作和ID)和一個提交按鈕的形式,我寫在2文本框的任何東西(用於測試),當我按提交時,表單通過POST方法將調用send.php頁面,這個頁面將向我們展示我在2個文本框中所寫的內容,我將向您展示的功能是用於連接服務器,並使用POST方法請求send.php並嘗試傳遞給服務器文本框變量的值。

下面是完整的功能:

int enviar(const char* action, const char* id){ 

#define ACTION "action=" 
#define ID "&id=" 

char head[500], buff_msg[500]; 
int s, len; 
struct sockaddr_in inf; 

if((s=socket(AF_INET, SOCK_STREAM, 0)) == -1) 
    return -1; 

inf.sin_family = AF_INET; 
inf.sin_port = htons(80); 
inf.sin_addr.s_addr = inet_addr("10.1.10.1"); 
memset(inf.sin_zero, 0, 8); 

if(connect(s, (struct sockaddr*)&inf, sizeof(inf)) == -1) 
    return -1; 

memset(head, 0, 500); 
memset(buff_msg, 0, 500); 

sprintf(head, "POST /page_called_by_the_index.php/HTTP/1.1\r\nContent-Length: %d\r\n", 
                strlen(ACTION)+strlen(action) 
                +strlen(ID)+strlen(id)); 
strcat(head, "host: the_server.com\r\n\r\n"); 
strcat(head, ACTION); 
strcat(head, action); 
strcat(head, ID); 
strcat(head, id); 

printf("Header HTTP[%d]:\n%s\n", strlen(cab), cab); 

len = send(s,head, strlen(cab), 0); 

if(len <= 0){ 
    perror("send"); 
    return 0; 
} 

printf("%d bytes have been sent\n", len); 

while((len=recv(s, buff_msg, 500, 0)) > 0){ 
    printf("%d bytes read:\n%s\n", len, buff_msg); 
    memset(buff_msg, 0, 500); 
} 

return 1;} 

頁眉要求是好事,因爲服務器送我回200 OK,但值 不解釋!

我感謝您的幫助。

+4

什麼是您看到的錯誤或問題? –

+0

您的緩衝區也包含\ r \ n。我希望它不是HTTP請求的實際名稱。請確保套接字在發送之前已連接。 –

回答

4

有幾個錯誤,在您的文章命令

Content-Lenght 

應該

Content-Length 

7+strlen(action)+3+strlen(id) 

是一個字符太短假設3 &id=(此需要4個字符,所以你的內容長度將省略你的id的最後一個字符)。如果您使用變量(或定義)來替換當前硬編碼長度的字符串會更安全

#define ACTION "action=" 
#define ID "&id=" 

sprintf(buffer, "POST /index.php HTTP/1.1\r\nContent-Length: %d\r\n", 
       sizeof(ACTION)-1+strlen(action)+sizeof(ID)-1+strlen(id)); 
strcat(buffer, "Host: www.testserv.com \r\n\r\n"); 
strcat(buffer, ACTION); 
strcat(buffer, action); 
strcat(buffer, ID); 
strcat(buffer, id); 
+0

+1 Content-Length的拼寫很棒# –

+0

嗯,您的提示改進了我的功能,但主要問題仍然存在,值不會發送到網站 – user2542813

+0

您從未說過您的問題是什麼。你可以更新你的帖子來顯示聲明/分配'緩衝區'並連接你的套接字的代碼嗎?如果您已經編寫了自己的服務器,那麼代碼也會很好。 – simonc