main.cpp

#include HttpReq.h
#include <string.h>
int main(void)
{
HttpRequest* Http;
char http_return[4096] = {0};
char http_msg[4096] = {0};
strcpy(http_msg, "http://目标主机的IP和要发送的请求信息"); if(Http->HttpGet(http_msg, http_return)){
std::cout << http_return << std::endl;
}
return 0;
}

下面是头文件,和cpp文件放到同一个文件夹 
HttpReq.h

//
// Created by thinker on 7/6/16.
// #ifndef PROJECT_HTTPREQ_H
#define PROJECT_HTTPREQ_H #endif //PROJECT_HTTPREQ_H #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); 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;
}; 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);
char* result=(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 result;
}
else if(ret > 0) {
sprintf(result,"%s%s",result,buf);
continue;
}
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] == '/') {
break;
} else {
strHostAddr[i] = strAddr[i];
}
} return strHostAddr;
} //从HTTP请求URL中获取HTTP请参数
char* HttpRequest::GetParamFromUrl(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* 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;
} //从HTTP请求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 = 80;
} else {
iPort = atoi(++strPort);
}
return iPort;
} //从HTTP请求URL中获取IP地址
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;
} //判断是否为点分十进制IP地址,否则通过域名地址获取IP地址
if((iCount == 3) && (iFlag == 0)) {
return strAddr;
} else {
struct hostent *he = gethostbyname(strAddr);
free(strAddr);
if (he == NULL) {
return NULL;
} else {
struct in_addr** addr_list = (struct in_addr **)he->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++) {
return inet_ntoa(*addr_list[i]);
}
return NULL;
}
}
} //检查SocketFd是否为可写不可读状态
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 > 0)
{
//判断SocketFd是否为可写不可读状态
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_SOCKET,SO_ERROR,error,&len);
if(ret == 0)
{
if(!strcmp(error, ""))
{
return iRet;//表示已经准备好的描述符数
}
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是否在可写字符集中:%d,是否在可读字符集中:%d\t(0表示不在)\n", __FILE__, __FUNCTION__, __LINE__, iW, iR);
}
}
else if(iRet == 0)
{
return 0;//表示超时
}
else
{
return -1;//select出错,所有描述符集清0
}
return -2;//其他错误
} //打印输出
void HttpRequest::DebugOut(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;
 
 

linux c++ 实现http请求的更多相关文章

  1. linux 模拟发http请求的例子

    curl -X POST --header "Content-Type: application/json" --header "Accept: */*" &q ...

  2. linux shell 模拟post请求

    Linux 下curl模拟Http 的get or post请求.   一.get请求 curl "http://www.baidu.com"  如果这里的URL指向的是一个文件或 ...

  3. LInux命令执行http请求

    Linux下提供了一些命令可以直接执行http请求,下面举例来介绍几个命令. http // GET请求 http http://127.0.0.1:2379/version http GET htt ...

  4. linux(centos8):firewalld对于请求会选择哪个zone处理?

    一,firewalld对一个请求会适用哪个zone? 当接收到一个请求时,firewalld具体使用哪个zone? firewalld是通过三个步骤来判断的: source,即:源地址 interfa ...

  5. 使用tcpdump+Wireshark(或Fiddler)做linux服务器的网络请求分析

    我们的服务器上,一般都没有窗口界面,这时候要抓包,用tcpdump是最方便的.而分析网络请求时,wireshark又是相当方便的,这时候我们就需要把它们两个一起来使用了. tcpdump 抓取数据 命 ...

  6. linux c++ curl https 请求并双向验证SSL证书

    1.配置curl https请求需要提供 CA证书.客户端证书和客户端秘钥,这三个文件的pem格式. 分别对应 curl_easy_setopt() 函数的 下面三个参数: CURLOPT_CAINF ...

  7. linux curl http get 请求中带有中文参数或者特殊字符处理

    在使用c++去请求http服务的时候,使用的是著名的curl工具提供的类库 libcurl,但是在使用的过程中发现,如果请求的参数值带了空格或者是参数是中文,会导致响应的回调函数没有被执行,虽然cur ...

  8. Linux下简单分析请求有没有进到本机的工具tcpdump(网络接口的数据包的头信息)

    可以通过这个工具快速分析出一个请求到底有没有进入到本机.信息有点简单,对于前期的分析比较有帮助.而对于详细的分析可以借助iptables的raw表进行日志分析. 参考: http://man.linu ...

  9. linux curl post/put请求

    案列: -X: 请求方式 --header: 请求header -d: 请求的数据 最后跟上请求的地址 curl -X PUT --header 'Content-Type: application/ ...

随机推荐

  1. LINUX学习之一基础篇

    1.计算机硬件五大单元:运算器.控制器.存储器.I/O设备 2.CPU种类:精简指令集(RISC)和复杂指令集(CISC) 3.1Byte=8bit,扇区大小为512bytes 4.芯片组通常分为两个 ...

  2. react -搭建服务

    import 'whatwg-fetch'; import 'es6-promise'; require('es6-promise').polyfill(); import * as common f ...

  3. POJ 1149 猪圈买猪 建图太强大!! 没有透彻领悟 慢慢消化

    PIGS Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 19575   Accepted: 8948 Description ...

  4. 序列模式挖掘--SPADE算法

  5. vue router 报错:NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated"}

    https://blog.csdn.net/weixin_43202608/article/details/98884620

  6. [CSP-S模拟测试]:真相(模拟)

    题目传送门(内部题106) 输入格式 第一行为一个正整数$T$,表示数据组数. 接下来$T$组数据,每组数据第一行一个正整数$n$表示$OIer$,接下来$n$行,第$i$行表示编号为$i$的人所说的 ...

  7. 错误“Object reference not set to an instance of an object”的解决方法

    在进行unity游戏制作的C#代码编写时,会遇到“NullReferenceException: Object reference not set to an instance of an objec ...

  8. C++入门经典-例2.15-逗号表达式的应用

    1:代码如下: // 2.15.cpp : 定义控制台应用程序的入口点. #include "stdafx.h" #include<iostream> using na ...

  9. Springboot集成Swagger操作步骤

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  10. c# 单元测试 ,对静态方法(static)和私有方法(private) 进行单元测试

    利用反射: /// <summary> /// 调用静态方法 /// </summary>akf /// <param name="t">类全名 ...