The C + + implementation sends an HTTP GET/POST request good

Source: Internet
Author: User

1. Brief introduction

Recently a simple look at the HTTP request knowledge, has been using QT to achieve, there is a special HTTP request Qnetworkaccessmanager class to deal with, the implementation is relatively simple, here is mainly to explain the use of C + + code to implement HTTP Get/post request.

An HTTP request message consists of a request line , a request header (header), and a request data * 3 parts, noting that the request header and request data need to be added in the middle of "\ r \ n "*. The general format of the request message is given.

(1) Request line

The request line includes a request method, a URL, and an HTTP protocol version of three parts.
the HTTP protocol request method has get, POST, HEAD, PUT, DELETE, OPTIONS, TRACE, CONNECT. The most common GET methods and POST methods are described here.
Get: Use the Get method when the client wants to read the document from the server. The Get method requires the server to place the URL-positioned resource in the data portion of the response message, which is sent back to the client. When using the Get method, the request parameter and the corresponding value are appended to the URL, using a question mark ("?" ) represents the end of the URL and the start of the request parameter, which is limited by the length of the pass parameter. For example,/index.jsp?id=100&op=bind.
Post: You can use the Post method when the client provides more information to the server. The Post method encapsulates the request parameters in the HTTP request data, appears as a name/value, and can transmit large amounts of data that can be used to transfer files.

(2) Request head

The request header consists of a keyword/value pair, one pair per line, a keyword and a value separated by a colon ":". The request header notifies the server that there is information about the client request, and the typical request headers are:
User-agent: The type of browser that generated the request.
Accept: A list of content types that the client can identify.
Host: The hostname of the request, which allows multiple domain names to be located in the same IP address as the virtual host.

(3) A blank line between the request header and the request data

After the request header is a blank line, you need to add a carriage return and a newline character--"\ r \ n", notifying the server that the request header is no longer available.
A blank line is required for a full HTTP request, otherwise the server will assume that the requested data has not been fully sent to the server and is in a waiting state.

(4) Request data

The request data is used in the Post method. The most commonly used request headers associated with request data are Content-type and content-length.

2, code of the road to send a GET request
BOOL Getipbydomainname (Char *szhost,char* szip) {wsadata wsadata; Hostent *phostent;int nadapter =0;struct sockaddr_in saddr;if (WSAStartup (0x0101, &wsadata)) {printf"GetHostByName error for host:\n");return FALSE; } phostent = gethostbyname (szhost);if (phostent) {if (Phostent->h_addr_list[nadapter]) {memcpy (&AMP;SADDR.SIN_ADDR.S_ADDR, Phostent->h_addr_list[nadapter], phostent->h_length);sprintf (Szip,"%s", Inet_ntoa (SADDR.SIN_ADDR)); } }else {DWORD dwerror = GetLastError ();CString Cserror;Cserror.format ("%d", dwerror); } wsacleanup ();return TRUE;}void Sendgetrequest () {Start the socket initialization; Wsadata Wdata; :: WSAStartup (Makeword (2,2), &wdata); Socket clientsocket = socket (Af_inet,1,0);struct Sockaddr_in serveraddr = {0};int ret=0;int addrlen=0; HANDLE hthread=0;Char *bufsend ="Get/check?+ parameter http/1.1\r\n""Connection:keep-alive\r\n""Accept-encoding:gzip, deflate\r\n""Accept-language:zh-cn,en,*\r\n""Host:www.baidu.com\r\n""User-agent:mozilla/5.0\r\n\r\n";Char addip[256] = {0}; Getipbydomainname ("Www.baidu.com", Addip); SERVERADDR.SIN_ADDR.S_ADDR = inet_addr (ADDIP); Serveraddr.sin_port = htons (80);; serveraddr.sin_family = af_inet;Char bufrecv[3069] = {0};int errNo =0; ErrNo = Connect (Clientsocket, (sockaddr*) &serveraddr,sizeof (SERVERADDR)); If (errno==0) { //if sent successfully, returns the number of bytes sent successfully; if (send (Clientsocket,bufsend,strlen (bufdata),0) >0) { cout<<"sent successfully \ n";;} //If the acceptance succeeds, the number of bytes accepted is returned; if (recv (CLIENTSOCKET,BUFRECV,3069,0) >0) { cout<<"Data accepted:" <<bufrecv <<endl; }} else {errno=wsagetlasterror ();} //socket Environment cleanup;:: WSACleanup ();}               

Send a POST request
The POST request simply replaces the above code with the char *bufsend = "Post/check http/1.1\ r\n "" Connection:keep-alive\r\n "" Accept-encoding:gzip, Deflate\r\n "" Accept-Language: Zh-cn,en,*\r\n "" content-length:114 \r\n "" content-type:application/x-www-form-urlencoded; Charset=utf-8\r\n "" Host:tmalarm.vemic.com\r\n" "User-agent:mozilla/5.0\r\n\r\n" "Request data \r< Span class= "Hljs-command" >\n\r\n ";      

The Post request can also write the request data in the request line, as with the GET request.

About whether the Get/post request was sent successfully

We can use the grab tool to see if the request we sent is successful, we can download the HttpAnalyzerStdV7 software to grab the packet, and the result of the return is the success of the request.

Request data in the Send request or request parameter with Chinese characters garbled

In our program encoding format is generally Unicode encoding, and the HTTP server (UTF-8) encoding is not the same, here you need to convert Chinese characters encoding format. About Unicode encoding and UTF-8 encoding problems You can see this article in C + + in Unicode and UTF-8 encoding.

Char *bufsend ="Get/check?&name=%s&password=%s http/1.1\r\n""connection:keep-alive\r\n" " Accept-encoding:gzip, deflate\r\n" " accept-language:zh-cn,en,*\r\ N " " host:www.baidu.com\r\n "" user-agent:mozilla/5.0\r\n\r\n "; CString cstrname = L"Piglet in the forward";  Const char* cName;  The UnicodeToUtf8 method converts the Unicode encoding to the UTF-8 format. CName = UnicodeToUtf8 (cstrname); char* PassWord = "123456";  Char bufdata[] = {0};sprintf_s (bufdata, N, Bufsend, CName, PassWord);  Finally, the result of converting Chinese to UTF-8 format is saved in the Bufdata array. 
Unicode Goto UTF-8char* UnicodeToUtf8 (const wchar_t* Unicode) { int len; len = WideCharToMultiByte (Cp_utf8, 0, Unicode ,-1, null, 0, null, null); char *szutf8 = (char*) malloc (len + 1); memset (SzUtf8, 0, Len + 1); WideCharToMultiByte (Cp_utf8, 0, Unicode,-1, SzUtf8, Len, null, null); return SzUtf8;}                  

http://blog.csdn.net/goforwardtostep/article/details/53318760

The C + + implementation sends an HTTP GET/POST request good

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.