使用Winsock2将GET请求发送到具有域HTTPS的Webstie

时间:2019-01-08 02:47:44

标签: c++ sockets https winsock2

我正在尝试向Web服务器发出GET请求,对于具有HTTP域的网站,我已经取得了成功。剩下的问题是我无法向具有HTTPS域的网站成功发送请求。

我必须在C ++中使用Winsock来完成此任务。这是我的对HTTP成功的代码:

void GET_request(URL url)
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;
    struct hostent* localHost;
    string request_header;
    char* localIP;
    int find_index;
    url.URL_detach();

    //Create a Request Header.
    request_header = "GET "+ url.path + " HTTP/1.0\r\n";
    request_header += "Host: " + url.host + "\r\n";
    request_header += "Connection: close\r\n";
    request_header += "Cache-Control: max-age=0\r\n";
    request_header += "Upgrade-Insecure-Requests: 1\r\n";
    request_header += "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\r\n";
    request_header += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n";
    request_header += "Accept-Encoding: gzip, deflate\r\n";
    request_header += "\r\n";

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
    }

    Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);         

    localHost = gethostbyname(url.host.c_str());                
    localIP = inet_ntoa(*(struct in_addr *)*localHost->h_addr_list);        //Return IP of HOST
    SockAddr.sin_port = htons(80);                                          //PORT 80 (HTTP)
    SockAddr.sin_family = AF_INET;                                          // TCP/IP
    SockAddr.sin_addr.s_addr = inet_addr(localIP);                          

    if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0)     
    {
        cout << "Could not connect to Server";
        system("pause");
    }

    send(Socket, request_header.c_str(), strlen(request_header.c_str()), 0);    


    int nDataLength;
    while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            Response_Header += buffer[i];
            i += 1;
        }
        find_index = Response_Header.find("</html>");
    }
    Response_Header.erase(find_index + 7);
    closesocket(Socket);
    WSACleanup();

}

0 个答案:

没有答案