简体   繁体   中英

Poco HTTPClientSession.receiveResponse returns status 200 but empty response in c++11?

I have a simple piece of code that connects to a basic HTTP server which always returns a plaintext JSON string. I used the Poco::net library which worked find until I upgraded to gcc 4.8 to access c++11 features. I have tried with various servers but the same behavior occurs so this is client side.

The response has status 200 OK, I even check the content length and this matches exactly what the server responds with, so some how the response message is received but it is not being made available.

  URI m_uri("http://www.bbc.co.uk");
  m_uri.setPort(80);
  HTTPClientSession m_session(m_uri.getHost(),m_uri.getPort());
  m_session.setKeepAlive(true);

  // send request
  HTTPRequest req(HTTPRequest::HTTP_GET, "/news/", HTTPMessage::HTTP_1_1);

  m_session.sendRequest(req);

  // get response
  HTTPResponse res;

  istream& is = m_session.receiveResponse(res);

  cout <<  res.getStatus() << "  " << res.getReason()  << " ,length =  " <<   res.getContentLength() <<  " , type = " <<res.getContentType() << ", keepalive = " << res.getKeepAlive() << endl;   // return 200 OK, correct content length on my real server, etc.
  cout << "good "  << is.good() << endl;   // istream is good, but gcount is 0

  // Copy response
  string results;
 // StreamCopier::copyToString(is, results);   // Fails with c++11

  is >> results;
  cout << results <<endl;     // blank
  if (results.empty())
      cout << "Error" << endl;       // yep, empty.   

Really lost at what to do. I tried compiling the latest Poco from source forcing to use gcc to no avail. Spent a couple of days trying to figure out but made no progress. I am on MacOSX Lion, gcc 4.8 Poco 4.3 and 4.6 tested

You can use this code in order to make string form of istream. Maybe this is solution for you. This is a function, you should pass std::stream and it converts to string and return result string.

        std::string convertFromStreamToString(std::istream &in){
        std::string ret;

        char buffer[4096];

        while (in.read(buffer, sizeof(buffer))){
            ret.append(buffer, sizeof(buffer));
        }

        ret.append(buffer, in.gcount());

        return ret;
    }

Did you compile the library correctly? I had the same problem on MinGW, tried it on MacOSX and it worked fine. Try reading the README thoroughly: https://github.com/sebastient/poco/blob/master/README

You might want to check the output of something like

std::cout << is.rdbuf() << std::endl;

is.gcount() is probably 0 because you didn't perform any unformatted input operation yet -- what does it show if you do is.getline() first?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM