title: HTTP request by sockets in C++
body: <p>I have one problem with HTTP request created by C++ sockets (Linux). I need to get some information's from API.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;ctype.h&gt;
  #include &lt;cstring&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sstream&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  
  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-&gt;h_addr == NULL) ) {
          cout &lt;&lt; "Error retrieving DNS information." &lt;&lt; endl;
          exit(1);
      }
  
      bzero(&amp;client, sizeof(client));
      client.sin_family = AF_INET;
      client.sin_port = htons( PORT );
      memcpy(&amp;client.sin_addr, host-&gt;h_addr, host-&gt;h_length);
  
      sock = socket(AF_INET, SOCK_STREAM, 0);
  
      if (sock &lt; 0) {
          cout &lt;&lt; "Error creating socket." &lt;&lt; endl;
          exit(1);
      }
  
      if ( connect(sock, (struct sockaddr *)&amp;client, sizeof(client)) &lt; 0 ) {
          close(sock);
          cout &lt;&lt; "Could not connect" &lt;&lt; endl;
          exit(1);
      }
  
      stringstream ss;
      ss &lt;&lt; "GET /3/movie/" &lt;&lt; 550 &lt;&lt; "?api_key=xxx HTTP/1.1\r\n"
         &lt;&lt; "Host: api.themoviedb.org\r\n"
         &lt;&lt; "Accept: application/json\r\n"
         &lt;&lt; "\r\n\r\n";
      string request = ss.str();
  
      if (send(sock, request.c_str(), request.length(), 0) != (int)request.length()) {
          cout &lt;&lt; "Error sending request." &lt;&lt; endl;
          exit(1);
      }
  
      char cur;
      while ( read(sock, &amp;cur, 1) &gt; 0 ) {
          cout &lt;&lt; cur;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>cout &lt;&lt; cur;
  </code></pre>
  
  <p>To:</p>
  
  <pre><code>cout &lt;&lt; cur &lt;&lt; endl;
  </code></pre>
  
  <p>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</p>