vhotmar
vhotmar

Reputation: 127

HTTP request by sockets in C++

I have one problem with HTTP request created by C++ sockets (Linux). I need to get some information's from API.

#include <iostream>
#include <ctype.h>
#include <cstring>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;

int sock;
struct sockaddr_in client;
int PORT = 80;

int main(int argc, char const *argv[])
{
    struct hostent * host = gethostbyname("api.themoviedb.org");

    if ( (host == NULL) || (host->h_addr == NULL) ) {
        cout << "Error retrieving DNS information." << endl;
        exit(1);
    }

    bzero(&client, sizeof(client));
    client.sin_family = AF_INET;
    client.sin_port = htons( PORT );
    memcpy(&client.sin_addr, host->h_addr, host->h_length);

    sock = socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {
        cout << "Error creating socket." << endl;
        exit(1);
    }

    if ( connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0 ) {
        close(sock);
        cout << "Could not connect" << endl;
        exit(1);
    }

    stringstream ss;
    ss << "GET /3/movie/" << 550 << "?api_key=xxx HTTP/1.1\r\n"
       << "Host: api.themoviedb.org\r\n"
       << "Accept: application/json\r\n"
       << "\r\n\r\n";
    string request = ss.str();

    if (send(sock, request.c_str(), request.length(), 0) != (int)request.length()) {
        cout << "Error sending request." << endl;
        exit(1);
    }

    char cur;
    while ( read(sock, &cur, 1) > 0 ) {
        cout << cur;
    }

    return 0;
}

But the problem is that it takes too long. It start writing response to console but it ends in 9/10 and after it takes about 30 seconds to end. When i tried to change in loop from:

cout << cur;

To:

cout << cur << endl;

Then it write a complete result but after it the program lags for a while. What is wrong with this code? When i tried get response by classic curl from terminal everything was OK. Thanks for your help

Upvotes: 0

Views: 28408

Answers (2)

Filipe
Filipe

Reputation: 21

You could have used HTTP/1.0 as the version on the request, since 1.0 version determines that the server should close the connection after each request.

Upvotes: 2

mark
mark

Reputation: 5469

Web server is probably holding the connection open awaiting your next HTTP request, which will never come. The server eventually times out and closes the connection. You can change this behavior by either:

  1. requesting the server close the connection with a Connection: close header line in the request

  2. parsing the response header to know when to stop reading once you have gotten the end of the response. See RFC 2616 Section 4.4 for the rules of how to detect the end of the response.

Upvotes: 4

Related Questions