程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> linux下HttpGet、HttpPost的C++實現

linux下HttpGet、HttpPost的C++實現

編輯:關於C++

#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請求失敗!\n");
	}
	
	memset(str, 0, BUFSIZE);	
	//安裝Tomcat
	if(Http->HttpGet("127.0.0.1", str)) {
		printf("%s\n", str);
	} else {
		printf("127.0.0.1 HttpGet請求失敗!\n");
	}

	free(str);
	return 0;
}


 

 

#ifndef __HTTP__
#define __HTTP__

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include       
#include 

#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);

	private:
		int   HttpRequestExec(const char* strMethod, const char* strUrl, const char* strData, char* strResponse);
		char* HttpHeadCreate(const char* strMethod, const char* strUrl, const char* strData);
		char* HttpDataTransmit(char *strHttpHead, const 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()
{
	
}


/**
*	功能描述:HttpGet請求
*	參數說明:
*				strUrl:     Http請求URL
*				strResponse:Http請求響應
*	返 回 值:
*				1表示成功
*				0表示失敗
**/
int HttpRequest::HttpGet(const char* strUrl, char* strResponse)
{
	return HttpRequestExec("GET", strUrl, NULL, strResponse);
}


/**
*	功能描述:HttpPost請求
*	參數說明:
*				strUrl:     Http請求URL
*               strData:    POST請求發送的數據
*				strResponse:Http請求響應
*	返 回 值:
*				1表示成功
*				0表示失敗
**/
int HttpRequest::HttpPost(const char* strUrl, const char* strData, char* strResponse)
{
	return HttpRequestExec("POST", strUrl, strData, strResponse);
}


//執行HTTP請求,GET或POST
int HttpRequest::HttpRequestExec(const char* strMethod, const char* strUrl, const char* strData, char* strResponse)
{
	//判斷URL是否有效
	if((strUrl == NULL) || (0 == strcmp(strUrl, ""))) {
		DebugOut("%s %s %d\tURL為空\n", __FILE__, __FUNCTION__, __LINE__); 
		return 0;
	}
	
	//限制URL長度
	if(URLSIZE < strlen(strUrl)) {
		DebugOut("%s %s %d\tURL的長度不能超過%d\n", __FILE__, __FUNCTION__, __LINE__, URLSIZE); 
		return 0;
	}
	
	//創建HTTP協議頭
	char* strHttpHead = HttpHeadCreate(strMethod, strUrl, strData);
	
	//判斷套接字m_iSocketFd是否有效,有效就直接發送數據
	if(m_iSocketFd != INVALID_SOCKET) {
		//檢查SocketFd是否為可寫不可讀狀態
		if(SocketFdCheck(m_iSocketFd) > 0) {
			char* strResult = HttpDataTransmit(strHttpHead, m_iSocketFd);
			if(NULL != strResult) {
				strcpy(strResponse, strResult);
				return 1;
			}
		}
	}

	//Create socket
	m_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 port
	int iPort = GetPortFromUrl(strUrl);
	if(iPort < 0) {
		DebugOut("%s %s %d\t從URL獲取端口失敗\n", __FILE__, __FUNCTION__, __LINE__); 
		return 0;
	}	
	char* strIP = GetIPFromUrl(strUrl);
	if(strIP == NULL) {
		DebugOut("%s %s %d\t從URL獲取IP地址失敗\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-blocking
	int 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;
	}

	//非阻塞方式連接
	int iRet = connect(m_iSocketFd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	if(iRet == 0) {
		char* strResult = 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;
}


//構建HTTP消息頭
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);
		sprintf(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;	
}


//發送HTTP請求並接受響應
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) //連接關閉
		{  		
			close(iSockFd);
			return NULL; 
		}
		else if(ret > 0) {						
			return buf; 
		}
		else if(ret < 0) //出錯
		{ 
			if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
				continue;
			}
			else {
				close(iSockFd);
				return NULL;
			}
		}
	}
}


//從HTTP請求URL中獲取主機地址,網址或者點分十進制IP地址
char* HttpRequest::GetHostAddrFromUrl(const char* strUrl)
{	
	char url[URLSIZE] = {0};
	strcpy(url, strUrl);
	
	char* strAddr = strstr(url, "http://");//判斷有沒有http://
	if(strAddr == NULL) {
		strAddr = strstr(url, "https://");//判斷有沒有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]="=" &#39;="" &#39;)="" break;="" }="" else="" strhostaddr[i]="strAddr[i];" return="" strhostaddr;="" 從http請求url中獲取http請參數="" char*="" httprequest::getparamfromurl(const="" strurl)="" char="" url[urlsize]="{0};" strcpy(url,="" strurl);="" straddr="strstr(url," "http:="" ");="" 判斷有沒有http:="" if(straddr="=" null)="" "https:="" 判斷有沒有https:="" !="NULL)" +="8;" int="" ilen="strlen(strAddr);" strparam="(char*)malloc(iLen+1);" memset(strparam,="" 0,="" ilen+1);="" ipos="-1;" for(int="" i="0;" )="" ||="" (strhostaddr[i]="" <="9" ))="" iflag="0;" free(strhostaddr);="" if(strlen(straddr)="" null;="" 判斷是否為點分十進制ip地址,否則通過域名地址獲取ip地址="" if((icount="=" 3)="" &&="" (iflag="=" 0))="" straddr;="" struct="" hostent="" *he="gethostbyname(strAddr);" free(straddr);="" if="" (he="=" in_addr**="" addr_list="(struct" in_addr="" **)he->h_addr_list;="" addr_list[i]="" inet_ntoa(*addr_list[i]);="" 檢查socketfd是否為可寫不可讀狀態="" httprequest::socketfdcheck(const="" isockfd)="" timeval="" timeout="" ;="" fd_set="" rset,wset;="" fd_zero(&rset);="" fd_zero(&wset);="" fd_set(isockfd,="" &rset);="" &wset);="" timeout.tv_sec="3;" timeout.tv_usec="500;" iret="select(iSockFd+1," &rset,="" &wset,="" null,="" &timeout);="" if(iret="" >="" 0)="" 判斷socketfd是否為可寫不可讀狀態="" iw="FD_ISSET(iSockFd,&wset);" ir="FD_ISSET(iSockFd,&rset);" if(iw="" !ir)="" error[4]="" socklen_t="" len="sizeof(error);" ret="getsockopt(iSockFd,SOL_SOCKET,SO_ERROR,error,&len);" if(ret="=" if(!strcmp(error,="" ""))="" iret;="" 表示已經准備好的描述符數="" debugout("%s="" %s="" %d\tgetsockopt="" error="" code:%d,error="" message:%s",="" __file__,="" __function__,="" __line__,="" errno,="" strerror(errno));="" failed.="" %d\tsockfd是否在可寫字符集中:%d,是否在可讀字符集中:%d\t(0表示不在)\n",="" iw,="" ir);="" 0;="" 表示超時="" -1;="" select出錯,所有描述符集清0="" -2;="" 其他錯誤="" 打印輸出="" void="" httprequest::debugout(const="" *fmt,="" ...)="" #ifdef="" __debug__="" va_list="" ap;="" va_start(ap,="" fmt);="" vprintf(fmt,="" ap);="" va_end(ap);="" #endif="" httprequest::m_isocketfd="INVALID_SOCKET;" <="" pre="">

<p>
</p><p>
</p></ilen+1;>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved