C/C++ HTTP,HTTPS实现GET和POST请求

HTTP GET和POST 实现过程
HTTP协议是在TCP基础上,加上HTTP协议头实现的

#include <QCoreApplication>
#include <qglobal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <limits.h>
#include <netdb.h>
#include <arpa/inet.h>
int socket_connect(char *server_IP, int port,char *local_IP)
{
    struct sockaddr_in localSockAddr;
    memset(&localSockAddr, 0, sizeof(struct sockaddr_in));
    localSockAddr.sin_family = AF_INET;
    localSockAddr.sin_addr.s_addr = inet_addr(local_IP);
    localSockAddr.sin_port = 0;
    //创建Socket
    int s = socket(AF_INET, SOCK_STREAM, 0); //TCP socket
    if(0 > s)
    {
        qDebug("Create Socket Error!");
        return -1;
    }
    //设置超时连接
    int timeout = 3000; //复杂的网络环境要设置超时判断
    int ret = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
    ret = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,sizeof(timeout));
    //指定服务器地址
    struct  sockaddr_in address;
    socklen_t sock_len;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(server_IP);
    address.sin_port = htons((unsigned short)port);
    sock_len = sizeof(address);
    bind(s,(struct sockaddr *)&localSockAddr, sizeof(localSockAddr));
    //连接
    if(-1 == connect(s,(struct sockaddr *)&address,sizeof(address)))
    {
        perror("ssssd");
        qDebug("Can Not Connect To Server IP!\n");
        return -1;
    }
    return s;
}
void closesocket(int sock)
{
    shutdown(sock, SHUT_RDWR);
    close(sock);
}
int main(int argc, char *argv[])
{
       QCoreApplication a(argc, argv);

       int sockfd=-1, ret;
       char buffer[2048];

       char local_file[256];
       FILE *fp;
       char request[2048];
       int send, totalsend;

       /* 客户程序开始建立 sockfd描述符 */
        if(sockfd)
        {
            closesocket(sockfd);
        }
       sockfd=socket_connect("192.168.1.4",8080,"192.168.11.129");
       if(sockfd<0)
       {
           qDebug("http SOCKET create fail. ");
           exit(1);
       }
      /* //------post data--------
       char buf[1000]="{"
        "'clientId':'postman'"
        "}";
       std::string strdata = buf;
       //-------post data end-----
       
       //-------post data length-------
       char lenbuf[200]={0};
       sprintf(lenbuf,"%d",strdata.length());
       std::string strLen=lenbuf;
       //-------post data length end-------
       
       //------http post head-------------
       std::string req="/webapp_war/book/testPost";
       std::string strSend = " HTTP/1.1\r\n"
                      "Host:192.168.1.4:8080\r\n"
                      "Cookie:16888\r\n"
                      "Content-Type:application/json\r\n"
                      "Charset:utf-8\r\n"
                      "Content-Length:";
       strSend = "POST " + req + strSend + strLen + "\r\n\r\n" + strdata;
       //------http post head end---------------*/
       
       //-------http head GET start,一定要用双\r\n结尾----------
        std::string strSend123 = "GET / HTTP/1.1\r\n"
                                 "Host:192.168.1.4:8080\r\n\r\n";
        printf("send=%s\n",strSend123.c_str());
        //-----http head Get end---------

        int ret=::send(sockfd, strSend123.c_str(), strSend123.length(), 0);
        if(ret>0)
        {
            printf("send success%d\r\n",ret);
        }
        else
        {
            printf("send fail\r\n");
            exit(-1);
        }
        char szBuffer[1024] = {0};
        while (true)
        {

             int nRet = ::recv(sockfd, szBuffer, sizeof(szBuffer), 0);
             if(nRet>0)
             {
                 printf("recv() returned %d bytes\n", nRet);
                 printf("received: %s\n", szBuffer);
             }
             else
             {
                printf("recv error\n");
                break;
             }
        }
       }

HTTPS GET和POST实现
https是在tcp基础上加了SSL,具体实现代码如下
实现https首先需要安装,openssl库我用的是openssl-1.1.1.tar.gz

#include <QCoreApplication>
#include <qglobal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <limits.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "iostream"

#define DEBUG 1

int socket_connect(char *server_IP, int port,char *local_IP)
{
    struct sockaddr_in localSockAddr;
    memset(&localSockAddr, 0, sizeof(struct sockaddr_in));
    localSockAddr.sin_family = AF_INET;
    localSockAddr.sin_addr.s_addr = inet_addr(local_IP);
    localSockAddr.sin_port = 0;

    //创建Socket
    int s = socket(AF_INET, SOCK_STREAM, 0); //TCP socket
    if(0 > s)
    {
        qDebug("Create Socket Error!");
        return -1;
    }
    //设置超时连接
    int timeout = 3000; //复杂的网络环境要设置超时判断
    int ret = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
    ret = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,sizeof(timeout));
    //指定服务器地址
    struct  sockaddr_in address;
    socklen_t sock_len;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(server_IP);
    address.sin_port = htons((unsigned short)port);
    sock_len = sizeof(address);
    bind(s,(struct sockaddr *)&localSockAddr, sizeof(localSockAddr));
    //连接
    if(-1 == connect(s,(struct sockaddr *)&address,sizeof(address)))
    {
        perror("ssssd");
        qDebug("Can Not Connect To Server IP!\n");
        return -1;
    }
    return s;
}
void closesocket(int sock)
{
    shutdown(sock, SHUT_RDWR);
    close(sock);
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

       int sockfd=-1, ret;
       char buffer[2048];
       char request[2048];
       int send, totalsend;
       SSL *ssl;
       SSL_CTX *ctx;    
       /* 客户程序开始建立 sockfd描述符 */
       sockfd=socket_connect("192.168.1.4",8443,"192.168.11.129");
       if(sockfd<0)
       {
           qDebug("http SOCKET create fail. ");
           exit(1);
       }

       /* SSL初始化 */
       SSL_library_init();
       SSL_load_error_strings();
       ctx = SSL_CTX_new(SSLv23_client_method());
       if (ctx == NULL) {
           ERR_print_errors_fp(stderr);
           exit(1);
       }
       //SSL_VERIFY_NONE,服务端验证客户端,客户端不需要验证服务端
         SSL_CTX_set_verify(ctx,SSL_VERIFY_NONE,NULL);

         //加载证书(客户端),第二个参数为本地证书名,第三个为路径
         int crt_ret=SSL_CTX_load_verify_locations(ctx,"ca.crt","/home/pwj/Desktop/cert_key/crt_lph/");
         if(crt_ret<0)
         {
             printf("load cert error\n");
             exit(-1);
         }
         //加载本地证书,这个是服务器端提供给客户端证书
        int use_crt1=SSL_CTX_use_certificate_file(ctx,"/home/pwj/Desktop/cert_key/crt_lph/client.crt",SSL_FILETYPE_PEM);
         if(use_crt1<=0)
         {
             ERR_print_errors_fp(stderr);
             exit(1);
         }
         //加载自己的私钥
         int use_key1=SSL_CTX_use_PrivateKey_file(ctx,"/home/pwj/Desktop/cert_key/crt_lph/client.key",SSL_FILETYPE_PEM);

         if(use_key1<=0)
         {
             ERR_print_errors_fp(stderr);
             exit(1);
         }
         //验证证书与私钥
         if(!SSL_CTX_check_private_key(ctx))

         {
             ERR_print_errors_fp(stderr);
             exit(1);
         }
       //===========================

       ssl = SSL_new(ctx);
       if (ssl == NULL) {
           ERR_print_errors_fp(stderr);
           exit(1);
       }

       /* 把socket和SSL关联 */
       ret = SSL_set_fd(ssl, sockfd);
       if (ret == 0) {
           ERR_print_errors_fp(stderr);
           exit(1);
       }

      /* RAND_poll();
       while (RAND_status() == 0) {
           unsigned short rand_ret = rand() % 65536;
           RAND_seed(&rand_ret, sizeof(rand_ret));
       }*/

       ret = SSL_connect(ssl);
       if (ret != 1) {
           ERR_print_errors_fp(stderr);
           exit(1);
       }
 /* //------post data--------
       char buf[1000]="{"
        "'clientId':'postman'"
        "}";
       std::string strdata = buf;
       //-------post data end-----
       
       //-------post data length-------
       char lenbuf[200]={0};
       sprintf(lenbuf,"%d",strdata.length());
       std::string strLen=lenbuf;
       //-------post data length end-------
       
       //------https post head-------------
       std::string req="/webapp_war/book/testPost";
       std::string strSend = " HTTP/1.1\r\n"
                      "Host:192.168.1.4:8443\r\n"
                      "Cookie:16888\r\n"
                      "Content-Type:application/json\r\n"
                      "Charset:utf-8\r\n"
                      "Content-Length:";
       strSend = "POST " + req + strSend + strLen + "\r\n\r\n" + strdata;
     
       printf("len=%d,POST:%s\n",strSend.length(),strSend.c_str());
       //------https post head end---------------*/
       std::string req="/webapp_war/book/list";

       std::string strSend = "/ HTTP/1.1\r\n"
                              "Host:14.215.177.39:443\r\n\r\n";

        strSend = "GET " + req + strSend;
        printf("len=%d,GET:%s\n",strSend.length(),strSend.c_str());*/

        /*发送https请求request */

           send = 0;
           totalsend = 0;
           int nbytes=0;
           sprintf(request,"%s",strSend.c_str());
           nbytes = strlen(request);
           while (totalsend < nbytes) {
               send = SSL_write(ssl, request + totalsend, nbytes - totalsend);
               if (send == -1) {
                   ERR_print_errors_fp(stderr);
                   exit(0);
               }
               totalsend += send;
               rintf("%d bytes send OK!\n", totalsend);
           }

           int nbytess=0;
           while(true)
           {
               nbytess = SSL_read(ssl, buffer, 2048);
               if(nbytess<=0)
               {
                   printf("ssl_read recv error\n");

                   break;
               }
               else
               {
                  printf("ssl_read,byte=%d\n",nbytess);
                  printf("rcv:%s\n",buffer);
               }
           }

    
       /* 结束通讯 */
       ret = SSL_shutdown(ssl);
       /*if (ret != 1) {
           ERR_print_errors_fp(stderr);
           exit(1);
       }*/
       close(sockfd);
       SSL_free(ssl);
       SSL_CTX_free(ctx);
       ERR_free_strings();
       //exit(0);

     }

    return a.exec();
}