純C++ 簡易GET/POST
純C++ 簡易GET/POST
資料來源:http://0cx.cc/c_sock_http.jspx
C++ 實現HTTP POST請求
HTTP POST方式是把請求參數放到HTTP請求報文的請求資料中,為了讓例子更容易看懂,僅保留HTTP Post關鍵參數,你還可以自訂一些參數,比如流覽器喜歡用的User-Agent,Accept,Connection等等
char *pHttpPost = “POST %s HTTP/1.1\r\n”
“Host: %s:%d\r\n”
“Content-Type: application/x-www-form-urlencoded\r\n”
“Content-Length: %d\r\n\r\n”
“%s”;
char* addr = “http://localhost/post.php”;
char* host = “127.0.0.1”;
int port = 80;
char* msg = “aaa=1&bbb=2”;
char strHttpPost[1024] = {0};
sprintf(strHttpPost, pHttpPost, addr, host, port, strlen(msg), msg);
//這裡忽略掉了socket連接代碼
send(sockClient, strHttpPost, strlen(strHttpPost), 0);
C++ 實現HTTP GET請求
HTTP GET方式是把請求參數放到HTTP請求報文的請求行URL中,所以請求行就是“GET /?aaa=1&bbb=2 HTTP/1.1\r\n”。URL最大長度通常流覽器取255,這和檔路徑最大長度有關。雖然HTTP允許更大長度,但不建議怎麼做,如果太長了,可以考慮換成POST方式
char *pHttpGet = “GET %s?%s HTTP/1.1\r\n”
“Host: %s:%d\r\n\r\n”;
char* addr = “http://localhost/get.php”;
char* host = “127.0.0.1”;
int post = 80;
char* msg = “aaa=1&bbb=2”;
char strHttpGet[1024] = {0};
sprintf(strHttpGet, pHttpGet, addr, msg, host, post);
//這裡忽略掉了socket連接代碼
send(sockClient, strHttpGet, strlen(strHttpGet), 0);