#include "HttpRequest.h" int main () {httprequest* Http = new httprequest;char* str = (char*) malloc (BUFSIZE); memset (str, 0, BUFSIZE), if (Http->httpget ("http://www.baidu.com", str)) {printf ("%s\n", str),} else {printf ("http:// Www.baidu.com httpget request failed!\n ");} memset (str, 0, BUFSIZE);//Install Tomcatif (http->httpget ("127.0.0.1", str)) {printf ("%s\n", str);} else {printf (" 127.0.0.1 HttpGet request failed!\n ");} Free (str); return 0;}
#ifndef __http__#define __http__#include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <netdb.h> #include <stdarg.h># Include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> # Include <sys/socket.h> #define BUFSIZE 41000#define urlsize 1024#define invalid_socket-1#define __debug__class Httprequest{public:httprequest (); ~httprequest (); void debugout (const char *fmt, ...); int HttpGet (const char* strurl, char* strresponse); int HttpPost (const char* strurl, const char* strdata, char* strresponse );p rivate:int httprequestexec (const char* strmethod, const char* strurl, const char* strdata, char* strresponse); char* H Ttpheadcreate (const char* strmethod, const char* strurl, const char* strdata); char* Httpdatatransmit (Char *strhttphead, C onst int isockfd), int getportfromurl (const char* strurl), char* getipfromurl (const char* strurl) char* getparamfromurl (const char* strurl); char* gethostaddrfromurl (const char* strurl); int SocketFdCheck ( const int ISOCKFD); static int m_isocketfd;}; #endif
#include "HttpRequest.h" Httprequest::httprequest () {}httprequest::~httprequest () {}/*** function Description: HttpGet Request * Parameter Description: * Strurl:http Request Url*strresponse:http Request Response * return Value: * * Indicates success *0 represents failure **/int httprequest::httpget (const char* strurl, char* strResp Onse) {return httprequestexec ("GET", strURL, NULL, strresponse);} /*** function Description: HttpPost Request * Parameter description: *strurl:http request url* strdata:post request sent data *strresponse:http Request Response * return Value: * * indicates success *0 Represents a failure **/int httprequest::httppost (const char* strurl, const char* strdata, char* strresponse) {return httprequestexec (" POST ", strURL, Strdata, strresponse);} Execute HTTP request, get or Postint httprequest::httprequestexec (const char* strmethod, const char* strurl, const char* strdata, Char * strresponse) {//Determine if URL is valid if (strURL = = NULL) | | (0 = = strcmp (strURL, ""))) {debugout ("%s%s%d\turl is empty \ n", __file__, __function__, __line__); return 0;} Limit URL length if (Urlsize < strlen (strURL)) {debugout ("%s%s%d\turl cannot be longer than%d\n", __file__, __function__, __line__, Urlsize); return 0;} Create HTTP protocol header char* StrhttpheAD = Httpheadcreate (Strmethod, strURL, strdata);//Determine if socket M_ISOCKETFD is valid, send data directly if (m_isocketfd! = invalid_socket) {// Check if SOCKETFD is writable and unreadable if (Socketfdcheck (M_ISOCKETFD) > 0) {char* strresult = Httpdatatransmit (Strhttphead, m_ ISOCKETFD); if (NULL! = strresult) {strcpy (strresponse, strresult); return 1;}}} Create socketm_isocketfd = INVALID_SOCKET;M_ISOCKETFD = SOCKET (af_inet, sock_stream, 0); if (M_isocketfd < 0) {debugout ("%s%s%d\tsocket error! Error Code:%d,error message:%s\n ", __file__, __function__, __line__, errno, Strerror (errno)); return 0;} Bind address and Portint iport = Getportfromurl (strURL), if (Iport < 0) {debugout ("%s%s%d\t failed to get port from URL \ n", __file__, _ _FUNCTION__, __line__); return 0;} char* StrIP = Getipfromurl (strURL), if (StrIP = = NULL) {debugout ("%s%s%d\t get IP address from URL failed \ n", __file__, __function__, __line __); return 0;} struct sockaddr_in servaddr;bzero (&servaddr, sizeof (SERVADDR)); servaddr.sin_family = af_inet; Servaddr.sin_port = htons (Iport); if (inet_Pton (Af_inet, StrIP, &servaddr.sin_addr) <= 0) {debugout ("%s%s%d\tinet_pton error! Error Code:%d,error message:%s\n ", __file__, __function__, __line__, errno, Strerror (errno)); Close (M_ISOCKETFD); M_ISOCKETFD = Invalid_socket; return 0; }//set Non-blockingint flags = fcntl (M_ISOCKETFD, F_GETFL, 0); if (Fcntl (M_ISOCKETFD, F_SETFL, flags| O_nonblock) = =-1) {close (M_ISOCKETFD); m_isocketfd = Invalid_socket;debugout ("%s%s%d\tfcntl error! Error Code:%d,error message:%s\n ", __file__, __function__, __line__, errno, Strerror (errno)); return 0;} Non-blocking mode connection int iRet = connect (m_isocketfd, (struct sockaddr *) &servaddr, sizeof (SERVADDR)); if (IRet = = 0) {char* strresu lt = Httpdatatransmit (Strhttphead, M_ISOCKETFD); if (NULL! = strresult) {strcpy (strresponse, strresult); free (strresult) ; return 1;} else {close (M_ISOCKETFD); M_ISOCKETFD = Invalid_socket;free (strresult); return 0;}} else if (IRet < 0) {if (errno! = einprogress) {return 0;}} IRet = Socketfdcheck (M_ISOCKETFD); if (IRet > 0) {char* strresult = Httpdatatransmit (Strhttphead, M_ISOCKETFD); if (NULL = = strresult) {close (M_ISOCKETFD); M_ISOCKETFD = Invalid_socket;return 0;} else {strcpy (strresponse, strresult); free (strresult); return 1;}} else {close (M_ISOCKETFD); m_isocketfd = Invalid_socket;return 0;} return 1;} Build HTTP message header char* httprequest::httpheadcreate (const char* strmethod, const char* strurl, const char* strdata) {char* Strhost = Gethostaddrfromurl (strURL); char* strparam = Getparamfromurl (strURL); char* strhttphead = (char*) malloc ( BUFSIZE); memset (strhttphead, 0, BUFSIZE); strcat (Strhttphead, strmethod); strcat (Strhttphead, "/"); strcat (Strhttphead, strparam); free (strparam); Strcat (Strhttphead, "http/1.1\r\n"); Strcat (Strhttphead, "Accept: */*\ r\n "); strcat (Strhttphead, "accept-language:cn\r\n"); strcat (Strhttphead, "user-agent:mozilla/4.0\r\n"); Strcat (Strhttphead, "Host:"); strcat (Strhttphead, strhost); Strcat (Strhttphead, "\ r \ n"); Strcat (Strhttphead, "cache-control:no-cache\r\n"); strcat (Strhttphead, "connection:keep-alive\r\n"), if (0 = = strcmp (strmethod, "POST")) {char len[8] = {0};unsigned Ulen = strlen (strdata); Sprin TF (len, "%d", Ulen), strcat (Strhttphead, "content-type:application/x-www-form-urlencoded\r\n"); Strcat (Strhttphead, "Content-length:"); strcat (Strhttphead, Len); strcat (Strhttphead, "\r\n\r\n"); strcat (Strhttphead, strdata); }strcat (Strhttphead, "\r\n\r\n"); free (strhost); return strhttphead;} Sends an HTTP request and accepts a response char* Httprequest::httpdatatransmit (char *strhttphead, const int isockfd) {char* buf = (char*) malloc ( BUFSIZE); memset (buf, 0, BUFSIZE); int ret = Send (ISOCKFD, (void *) Strhttphead,strlen (strhttphead) +1,0); Free (Strhttphead), if (Ret < 0) {debugout ("%s%s%d\tsend error! Error Code:%d,error message:%s\n ", __file__, __function__, __line__, errno, Strerror (errno)); Close (ISOCKFD); return NULL; }while (1) {ret = recv (ISOCKFD, (void *) buf, bufsize,0); if (ret = = 0)//connection Close {close (ISOCKFD); return NULL;} else if (Ret > 0) {return buf;} else if (Ret &Lt 0)//error {if (errno = = Eintr | | errno = = Ewouldblock | | errno = eagain) {continue;} else {close (ISOCKFD); return NULL;}}} Get the host address, url, or dotted decimal IP address from the HTTP request URL char* httprequest::gethostaddrfromurl (const char* strurl) {char Url[urlsize] = {0}; strcpy (URL, strurl); char* straddr = strstr (URL, "http://");//Determine if there is no http://if (straddr = = NULL) {straddr = strstr (URL, "http s://");//Judging there is no https://if (straddr! = NULL) {straddr + = 8;}} else {straddr + = 7;} if (straddr = = NULL) {straddr = URL;} int ilen = strlen (straddr); char* strhostaddr = (char*) malloc (ilen+1); memset (strhostaddr, 0, ilen+1); for (int i=0; i< ilen+1; i++) {if (straddr[i] = = '/') {break;} else {strhostaddr[i] = Straddr[i];}} return strhostaddr;} Get HTTP from HTTP request URL parameter char* httprequest::getparamfromurl (const char* strurl) {char url[urlsize] = {0};strcpy (URL, strURL); char* straddr = strstr (URL, "http://");//Determine if there is no http://if (straddr = = NULL) {straddr = strstr (URL, "https://");// Determine if there is https://if (straddr! = NULL) {straddr + = 8;}} else {straddr + = 7;} if (strAddr = = NULL) {straddr = URL;} int ilen = strlen (straddr); char* strparam = (char*) malloc (ilen+1); memset (strparam, 0, ilen+1); int iPos = -1;for (int i=0; i <iLen+1; i++) {if (straddr[i] = = '/') {IPos = I;break;}} if (IPos = =-1) {strcpy (Strparam, "");;} else {strcpy (strparam, straddr+ipos+1);} return strparam;} Gets the port number from the HTTP request URL int httprequest::getportfromurl (const char* strurl) {int iport = -1;char* Strhostaddr = Gethostaddrfromurl (strURL); if (strhostaddr = = NULL) {return-1;} Char Straddr[urlsize] = {0};strcpy (straddr, strhostaddr); free (strhostaddr); char* strport = STRCHR (straddr, ': '); if ( Strport = = NULL) {iport = +;} else {iport = Atoi (++strport);} return iport;} Obtain the IP address from the HTTP request URL char* httprequest::getipfromurl (const char* strurl) {char* strhostaddr = Gethostaddrfromurl (strUrl int ilen = strlen (strhostaddr); char* straddr = (char*) malloc (ilen+1); memset (straddr, 0, ilen+1); int iCount = 0;int Iflag = 0;for (int i=0; i<ilen+1; i++) {if (strhostaddr[i] = = ': ') {break;} Straddr[i] = strhostaddr[I];if (strhostaddr[i] = = '. ') {icount++;continue;} if (Iflag = = 1) {continue;} if ((strhostaddr[i] >= ' 0 ') | | (Strhostaddr[i] <= ' 9 ')) {iflag = 0;} else {iflag = 1;}} Free (STRHOSTADDR); if (strlen (straddr) <= 1) {return NULL;} Determine whether to point the decimal IP address, otherwise obtain the IP address via the domain address if ((ICount = = 3) && (Iflag = = 0)) {return straddr;} else {struct hostent *he = Geth Ostbyname (STRADDR); free (STRADDR), if (he = null) {return null;} else {struct in_addr** addr_list = (struct in_addr * *) he-& Gt;h_addr_list; for (int i = 0; Addr_list[i]! = NULL; i++) {return Inet_ntoa (*addr_list[i]);} return NULL;}}} Checks whether the SOCKETFD is writable, unreadable, int httprequest::socketfdcheck (const int isockfd) {struct timeval timeout; fd_set Rset,wset; Fd_zero (&rset); Fd_zero (&wset); Fd_set (ISOCKFD, &rset); Fd_set (ISOCKFD, &wset); Timeout.tv_sec = 3;timeout.tv_usec = 500;int IRet = Select (Isockfd+1, &rset, &wset, NULL, &timeout); if (IRet &G T 0) {//Determine if SOCKETFD is a writable unreadable state int iW = Fd_isset (isockfd,&wset); int iR = Fd_isset (iSocKfd,&rset); if (IW &&!ir) {char error[4] = ""; socklen_t len = sizeof (error); int ret = getsockopt (isockfd,sol_so Cket,so_error,error,&len), if (ret = = 0) {if (!strcmp (ERROR, "")) {return iret;//represents the number of descriptors already prepared}else {debugout ("%s%s%d \tgetsockopt error Code:%d,error message:%s ", __file__, __function__, __line__, errno, Strerror (errno));}} Else{debugout ("%s%s%d\tgetsockopt failed. Error Code:%d,error message:%s ", __file__, __function__, __line__, errno, Strerror (errno));}} Else{debugout ("%s%s%d\tsockfd is in the writable character set:%d, whether in the readable character set:%d\t (0 means no) \ n", __file__, __function__, __line__, IW, IR);} else if (IRet = = 0) {return 0;//indicates a time-out}else{return-1;//select error, all descriptions Fu Giuqing 0}return-2;//Other errors}//print output void HttpRequest::D Ebugout (const char *FMT, ...) {#ifdef __debug__va_list Ap;va_start (AP, FMT); vprintf (FMT, AP); Va_end (AP); #endif}int httprequest::m_isocketfd = Invalid_socket;
Code: http://download.csdn.net/detail/dezhihuang/9515232
Reference Documentation: http://blog.chinaunix.net/uid-27766566-id-3463221.html
C + + implementation of HttpGet and HttpPost under Linux