HTTP Post Using C

來源:互聯網
上載者:User

HTTP post requests are very easy to handle by using HTML forms and other languages where they are natively supported. Basically, a request is nothing but a socket-based communication between the browser and Web server. The Hypertext Transfer Protocol, HTTP/1.1 (http://www.w3.org/Protocols/rfc2616/rfc2616.html), documents the standards.

 

A client request looks like the following:

POST<br /><Post program><br /> HTTP/1.0<br />Accept: */*<br />User-Agent: Mozilla/4.0<br />Content-Length: <length of parameters><br />Accept-Language: en-us<br />Accept-Encoding: gzip, deflate<br />Host: <hostname><br />Content-Type: application/x-www-form-urlencoded<br />Authorization: Basic <base64 encoded login name : password></p><p><param1=val1¶m2=val2><br />

 

The server responds with the header part and body part of the message.

 

Header part:

 

HTTP/1.0 200<br />Date: Thu 9 Dec 2004 12:23:50 GMT<br />Server: Archive-Appliance<br />Connection: close<br />Content-type: text/xml<br />

 

The HTTP/1.0 200 status states everything went okay. For instance, it can be HTTP/1.0 404 if you made a wrong request. The body part is whatever the post script or program's output is.

 

/*<br /> * http_post.cpp<br /> *<br /> * by Uday Chitragar - 2004/Dec/01<br /> *<br /> * This software is provided 'as-is', without any express or implied<br /> * warranty. In no event will the authors be held liable for any<br /> * damages arising from the use of this software.<br /> *<br /> * Permission is granted to anyone to use this software for any<br /> * purpose, including commercial applications, and to alter it and<br /> * redistribute it freely, subject to the following restrictions:<br /> *<br /> * 1. The origin of this software must not be misrepresented; you must<br /> * not claim that you wrote the original software. If you use this<br /> * software in a product, an acknowledgment in the product documentation<br /> * would be appreciated but is not required.<br /> *<br /> * 2. Altered source versions must be plainly marked as such, and<br /> * must not be misrepresented as being the original software.<br /> *<br /> * 3. This notice may not be removed or altered from any source<br /> * distribution.<br /> *<br /> * */</p><p>/*<br /> * Notes:<br /> * This source demonstrates sending HTTP POST request to webserver from C++<br /> * This uses sockets hence can be compiled on Linux, UNIX, Win<br /> */</p><p>#define LINUX_OS<br />// #define WIN_OS<br />#define _DEBUG_PRINT(X) /* X */</p><p>//For commn<br />#include <iostream><br />#include <string><br />#include <stdlib.h><br />#include <assert.h></p><p>#ifdef LINUX_OS<br /> #include <netdb.h><br />#endif</p><p>#ifdef WIN_OS<br /> #include <Winsock2.h><br />#endif</p><p>#define SEND_RQ(MSG) /<br /> /*cout<<send_str;*/ /<br /> send(sock,MSG,strlen(MSG),0);</p><p>using namespace std;<br />//<exe> hostname api parameters<br />int request (char* hostname, char* api, char* parameters, string& message)<br />{</p><p>#ifdef WIN_OS<br />{<br />WSADATAWsaData;<br />WSAStartup (0x0101, &WsaData);<br />}<br />#endif</p><p> sockaddr_in sin;<br /> int sock = socket (AF_INET, SOCK_STREAM, 0);<br /> if (sock == -1) {<br />return -100;<br />}<br /> sin.sin_family = AF_INET;<br /> sin.sin_port = htons( (unsigned short)80);</p><p> struct hostent * host_addr = gethostbyname(hostname);<br /> if(host_addr==NULL) {<br /> _DEBUG_PRINT( cout<<"Unable to locate host"<<endl );<br /> return -103;<br /> }<br /> sin.sin_addr.s_addr = *((int*)*host_addr->h_addr_list) ;<br /> _DEBUG_PRINT( cout<<"Port :"<<sin.sin_port<<", Address : "<< sin.sin_addr.s_addr<<endl);</p><p> if( connect (sock,(const struct sockaddr *)&sin, sizeof(sockaddr_in) ) == -1 ) {<br /> _DEBUG_PRINT( cout<<"connect failed"<<endl ) ;<br /> return -101;<br /> }</p><p> string send_str;</p><p> SEND_RQ("POST ");<br /> SEND_RQ(api);<br /> SEND_RQ(" HTTP/1.0/r/n");<br /> SEND_RQ("Accept: */*/r/n");<br /> SEND_RQ("User-Agent: Mozilla/4.0/r/n");</p><p> char content_header[100];<br /> sprintf(content_header,"Content-Length: %d/r/n",strlen(parameters));<br /> SEND_RQ(content_header);<br /> SEND_RQ("Accept-Language: en-us/r/n");<br /> SEND_RQ("Accept-Encoding: gzip, deflate/r/n");<br /> SEND_RQ("Host: ");<br /> SEND_RQ("hostname");<br /> SEND_RQ("/r/n");<br /> SEND_RQ("Content-Type: application/x-www-form-urlencoded/r/n");</p><p> //If you need to send a basic authorization<br /> //string Auth = "username:password";<br /> //Figureout a way to encode test into base64 !<br /> //string AuthInfo = base64_encode(reinterpret_cast<const unsigned char*>(Auth.c_str()),Auth.length());<br /> //string sPassReq = "Authorization: Basic " + AuthInfo;<br /> //SEND_RQ(sPassReq.c_str());</p><p> SEND_RQ("/r/n");<br /> SEND_RQ("/r/n");<br /> SEND_RQ(parameters);<br /> SEND_RQ("/r/n");</p><p> _DEBUG_PRINT(cout<<"####HEADER####"<<endl);<br /> char c1[1];<br /> int l,line_length;<br /> bool loop = true;<br /> bool bHeader = false;</p><p> while(loop) {<br /> l = recv(sock, c1, 1, 0);<br /> if(l<0) loop = false;<br /> if(c1[0]=='/n') {<br /> if(line_length == 0) loop = false;</p><p> line_length = 0;<br /> if(message.find("200") != string::npos)<br /> bHeader = true;</p><p> }<br /> else if(c1[0]!='/r') line_length++;<br /> _DEBUG_PRINT( cout<<c1[0]);<br /> message += c1[0];<br /> }</p><p> message="";<br /> if(bHeader) {</p><p> _DEBUG_PRINT( cout<<"####BODY####"<<endl) ;<br /> char p[1024];<br /> while((l = recv(sock,p,1023,0)) > 0) {<br /> _DEBUG_PRINT( cout.write(p,l)) ;<br /> p[l] = '/0';<br /> message += p;<br /> }</p><p> _DEBUG_PRINT( cout << message.c_str());<br /> } else {<br /> return -102;<br /> }</p><p> #ifdef WIN_OS<br /> WSACleanup( );<br /> #endif</p><p> return 0;<br />}</p><p>int main(){<br /> string message;<br /> int request ("www.somesite.com", "/post_url.pl", "search=hello&date=todat", string& message);<br /> // message contains response!</p><p>}</p><p>

 

From http://www.codeguru.com/cpp/i-n/internet/http/article.php/c8813/

 

(continued)

 

 

The code in this article is based on these standards and has been tested to act as an HTTP client to make a post request and retrieve the response from Web server. Through the open socket, write and read are simple tasks to perform. Sending the requests in order and in the correct format is essential.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.