Requêtte GET en c++

Requêtte GET en c++

Le problème exposé dans ce sujet a été résolu.

Bonjour, j’essaye depuis quelques heures de crée un petit programme pour faire des requête http et afficher le contenu d’une page web, dans ce cas, google.ca (.ca = Canada). Le résultat espéré final serait de pouvoir télécharger des vidéos sur youtube.. Un peu loin du but :lol:

Pas si pire pour un débutant.. :D

Donc,
le problème c’est que je n’arrive pas a afficher le code source de la page.. xd vous allez peut-être me dire que tu aurais pu utiliser boost::asio ou même cURL mais je trouve qu’on utilisant un système de socket() brut, on apprend mieux à connaitre ce qui se passe en dessous du moteur. Je pense que le problème viens de la requête que j’ai faite, surement mal écrite; Si quelqu’un pourrais me l’expliquer :)

Code d’erreur (merci debug): "Send() send a different number of bytes than expected 40" ligne 76-77 (Le programme se compile)

Merci :P

C0de :

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <WS2tcpip.h>
#include <iostream>
#include <string>
#include <Windows.h>

#pragma comment(lib,"ws2_32.lib")

using std::cout;
using std::endl;


void startUp();

int main()
{
    //wsaDate  ..
    startUp();


    //S0cket
    SOCKET ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (ListeningSocket == -1)
    {
        cout <<
            "Error at: Socket Error.. "
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout <<
            "Listening Socket Created Succefully!"
            << endl;
    }

    //C0nnection
    const char* IpAddress = "66.33.196.149";
    struct sockaddr_in  hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(80);
    //hint.sin_addr.s_addr  = inet_addr(IpAddress); //Don't Use That _'TT_
    inet_pton(AF_INET, IpAddress, &hint.sin_addr);

    bind(ListeningSocket, (sockaddr*)&hint, sizeof(hint));
    int ConnectionHandleEst = connect(ListeningSocket, (struct sockaddr*)&hint, sizeof(hint));
    if (ConnectionHandleEst != 0)
    {
        cout <<
            "Error at : Can't connect to server Error "
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout <<
            "Connection established!"
            << endl;
    }
    //Request
    std::string request;
    request += "GET /HTTP/1.1\r\n";
    request += "Host: iamawesome.com\r\n";
    //request += "Connection: keep-alive";
    request += "\r\n";


    int Connection = send(ListeningSocket, request.c_str(), request.size() + 1, 0);
    if (Connection < 0)
    {
        cout <<
            "Send() sent a different number of bytes than expected " <<
            +request.length()
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }

    //Get Resp0nse
    char buffer[4096];
    int resp_length;
    std::string response;

    while (true)
    {
        resp_length = recv(ListeningSocket, buffer, 4096, 0);
        if (resp_length <= 0)
        {
            break;
        }
        response += std::string(buffer).substr(0, resp_length);
    }


    cout << response << endl;

    //Close s0cket
    closesocket(ListeningSocket);
    WSACleanup();

    system("PAUSE");

    return 0;
}

void startUp() {
    WSADATA wsaData;
    int wsaResult = MAKEWORD(2, 2);
    int iResult = WSAStartup(wsaResult, &wsaData);
    if (iResult != 0) {
        cout <<
            "Error at: Initializing Winsock.., Winsock 2.2 may be not supported by your system or simply not installed"
            << endl;
        return;

    }
    else
    {
        cout <<
            "[Winsock]Status : "
            << wsaData.szSystemStatus << endl;
    }
}
}
+0 -0

....

Résolu, il fallait ajouter un <= au lieu de < seulement a la ligne 88

Mais j’ai tout de même une quéstion, est-ce une bonne façon d’envoyer une requête GET de cette façon, bien structurer ?

J’ai ça comment réponse :

HTTP/1.0 400 Bad Request Content-Length: 54 Content-Type: text/html; charset=UTF-8 Date: Tue, 30 Jan 2018 00:24:57 GMT

Et comment dois je faire pour envoyer une requête vers zestedesavoir.com par exemple ou sur un site en local (127.0.0.1) ?

Résulat (iamawesome.com, 66.33.196.149) :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!doctype html>
<html>
<head>
    <title>Site not found &middot; DreamHost</title>
    <meta http-equiv="cache-control" content="no-cache" />
    <meta name="description" content="The owner of this domain has not yet uploaded their website." />
    <link rel="stylesheet" href="https://securendn.a.ssl.fastly.net/newpanel/css/singlepage.css" />
</head>
<body>
    <div class="page page-missing">
        <h1>Site Not Found</h1>

        <p>Well, this is awkward. The site you're looking for is not here.</p>
        <p><small>Is this your site? <a href="http://wiki.dreamhost.com/Site_not_found">Get more info</a> or <a href="https://panel.dreamhost.com/index.cgi?tree=support.msg">contact support</a>.</small></p>

        <a href="http://www.dreamhost.com/" class="logo">DreamHost</a>
    </div>
</body>
</html>

`

http://image.noelshack.com/fichiers/2018/05/2/1517276896-http-get-error-1.png

http://www.noelshack.com/2018-05-2-1517276896-http-get-error-1.png

Dernière version :

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <WS2tcpip.h>
#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>

#pragma comment(lib,"ws2_32.lib")

using std::cout;
using std::endl;
using std::ofstream;
#define MAX_BUFFLEN 4096
void startUp();

int main()
{
    //wsaDate  ..
    startUp();


    //S0cket
    SOCKET ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (ListeningSocket == -1)
    {
        cout <<
            "Error at: Socket Error.. "
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout <<
            "Listening Socket Created Succefully!"
            << endl;
    }

    //C0nnection
    const char* IpAddress = "66.33.196.149";
    struct sockaddr_in  hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(80);
    //hint.sin_addr.s_addr  = inet_addr(IpAddress); //Don't Use That _'TT_
    inet_pton(AF_INET, IpAddress, &hint.sin_addr);

    bind(ListeningSocket, (sockaddr*)&hint, sizeof(hint));
    int ConnectionHandleEst = connect(ListeningSocket, (struct sockaddr*)&hint, sizeof(hint));
    if (ConnectionHandleEst != 0)
    {
        cout <<
            "Error at : Can't connect to server Error "
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout <<
            "Connection established!"
            << endl;
    }
    //Request
    std::string request;
    request += "GET /HTTP/1.0\r\n";
    request += "Host: iamawesome.com\r\n";
    //request += "Connection: keep-alive";
    request += "\r\n";


    int Connection = send(ListeningSocket, request.c_str(), request.size() + 1, 0);
    if (Connection < 0)
    {
        cout <<
            "Send() sent a different number of bytes than expected " <<
            +request.length()
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout << "\nContent:\n" 
            <<
            request
            << endl;
    }

    //Get Resp0nse
    char buffer[4096];
    int resp_length;
    std::string response;

    ofstream myfile;
    myfile.open("out_.html");

    if (Connection != SOCKET_ERROR)
    {
        do
        {
        //ZeroMemory(buffer, 4096);
        memset(buffer, 0, 4096);
        resp_length = recv(ListeningSocket, buffer, 4096, 0); 
        response += buffer;

        } while (resp_length != 0);
    }
    cout << response << endl;



    myfile << response;
    myfile.close();

    //Close s0cket
    closesocket(ListeningSocket);
    WSACleanup();
    system("PAUSE");

    return 0;
}

void startUp() {
    WSADATA wsaData;
    int wsaResult = MAKEWORD(2, 2);
    int iResult = WSAStartup(wsaResult, &wsaData);
    if (iResult != 0) {
        cout <<
            "Error at: Initializing Winsock.., Winsock 2.2 may be not supported by your system or simply not installed"
            << endl;
        return;

    }
    else
    {
        cout <<
            "[Winsock]Status : "
            << wsaData.szSystemStatus << endl;
    }
}
+0 -0

Et comment dois je faire pour envoyer une requête vers zestedesavoir.com par exemple ou sur un site en local (127.0.0.1) ?

PixarFilmz-

Tu dois d’abord résoudre zestedesavoir.com (DNS) pour obtenir son adresse IP et changer ta requête GET pour y mettre l’Host qui va bien.

Pour 127.0.0.1, pas de résolution à faire, mais tu dois t’assurer que tu as un serveur web qui tourne en local pour que cela fonctionne.

Essaie de voir de ce côté-là : https://msdn.microsoft.com/en-us/library/windows/desktop/ms682016(v=vs.85).aspx

Je sais vraiment pas comment faire là .. :(

J’obtient toujours la même réponse du serveur 400 Bad Request

J’envoya ça :

1
2
3
4
request += "GET HTTP/1.0\r\n";
request += "Host: zestedesavoir.com\r\n";
request += "Connection: close\r\n";
request += "\r\n";

Comme réponse:

1
2
3
4
5
  HTTP/1.1 400 Bad Request Server: nginx/1.12.2 Date: Wed, 31 Jan 2018 00:27:20 GMT Content-
  Type: text/html Content-Length: 173 Connection: close X-Xss-Protection: 1 X-Content-Type-
  Options: nosniff
  400 Bad Request
  nginx/1.12.2

Je vois pas ce qui cloche avec la requette..? ip92.243.7.44

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <WS2tcpip.h>
#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>

#pragma comment(lib,"ws2_32.lib")


using std::cout;
using std::endl;
using std::ofstream;
#define MAX_BUFFLEN 4096
void StartUp();

int main()
{
    //wsaDate  ..
    StartUp();


    //S0cket
    SOCKET ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (ListeningSocket < 0)
    {
        cout <<
            "Error at: Socket Creation ListeningSocket().. "
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout <<
            "Listening Socket Created Succefully!"
            << endl;
    }

    //C0nnection
    //----------ARGUMENTS-----------------------------------------------------------------------
    std::string IpAddress = "92.243.7.44";
    struct sockaddr_in  hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(80);
    //hint.sin_addr.s_addr  = inet_addr(IpAddress); //Don't Use That _'TT_
    inet_pton(AF_INET, IpAddress.c_str(), &hint.sin_addr);
    //----------ARGUMENTS-----------------------------------------------------------------------

    int ConnectionHandleEstablishement = connect(ListeningSocket, (struct sockaddr*)&hint, sizeof(hint));
    if (ConnectionHandleEstablishement < 0)
    {
        cout <<
            "Error at : Can't Connect ConnectionHandleEstablishement() Error"
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout <<
            "Connection established!"
            << endl;
    }
    //----------REQUEST-----------------------------------------------------------------------
    std::string request;
    request += "GET HTTP/1.0\r\n";
    request += "Host: zestedesavoir.com\r\n";
    request += "Connection: close\r\n";
    request += "\r\n";
    //request += "GET /HTTP/ 1.1 200 OK\r\nHost: zestedesavoir.com\r\n\r\n";
    //----------REQUEST-----------------------------------------------------------------------


    int Connection = send(ListeningSocket, request.c_str(), request.length(), 0);
    if (Connection < 0)
    {
        cout <<
            "Send() sent a different number of bytes than expected " <<
            +request.length()
            << endl;
        closesocket(ListeningSocket);
        WSACleanup();
        return 1;
    }
    else
    {
        cout << "\nRequest:\n" 
            <<
            request
            << endl;
    }

    //Get Resp0nse
    char buffer[4096];
    int resp_length = MAX_BUFFLEN;
    std::string response;

    ofstream myfile;
    myfile.open("out_.html");

        do
        {
        memset(buffer, 0, 4096);
        resp_length = recv(ListeningSocket, buffer, 4096, 0); 
        response += buffer;

        } while (resp_length <= 0);

    cout << response << endl;

    myfile << response;
    myfile.close();

    //Close s0cket
    closesocket(ListeningSocket);
    WSACleanup();
    system("PAUSE");

    return 0;
}

void StartUp() {
    WSADATA wsaData;
    int wsaResult = MAKEWORD(2, 2);
    int iResult = WSAStartup(wsaResult, &wsaData);
    if (iResult != 0) {
        cout <<
            "Error at: Initializing Winsock.., Winsock 2.2 may be not supported by your system or simply not installed"
            << endl;
        return;

    }
    else
    {
        cout <<
            "[Winsock]Status : "
            << wsaData.szSystemStatus << endl;
    }
}
+0 -0

Aaahhh… C’est ta requête qui n’est pas bonne. Essaie ça :

1
2
3
4
request += "GET / HTTP/1.0\r\n";
request += "Host: zestedesavoir.com\r\n";
request += "Connection: close\r\n";
request += "\r\n";

Tu as oublié de préciser le path après ta méthode GET. Utilise HTTP/1.1 aussi.

Connectez-vous pour pouvoir poster un message.
Connexion

Pas encore membre ?

Créez un compte en une minute pour profiter pleinement de toutes les fonctionnalités de Zeste de Savoir. Ici, tout est gratuit et sans publicité.
Créer un compte