Reputation: 4459
For some reason I need to use a blocking call to perform image accessing from google's server. However, QNetworkAccessManager seems to be async, though there are many work arounds, like calling a eventLoop.exec(); many people online suggested me not to do so.
So I am trying to use TCP socekt. I want to access the image here:
http://mt1.google.com/vt/lyrs=y&x=0&y=0&z=0
And here is my code:
socket = new QTcpSocket(this);
socket->connectToHost("mt1.google.com", 80, QIODevice::ReadWrite);
if(socket->waitForConnected(5000))
{
qDebug() << "Connected!";
// send
socket->write("/vt/lyrs=y&x=0&y=0&z=0");
socket->waitForBytesWritten(1000);
socket->waitForReadyRead(3000);
qDebug() << "Reading: " << socket->bytesAvailable();
// get the data
qDebug() << socket->readAll();
// close the connection
socket->close();
}
else
{
qDebug() << "Not connected!";
}
But it seems to working at all? What should I write through the tcp socket to get the image?
Upvotes: 0
Views: 273
Reputation: 1711
TCP provides only the transport mechanism. Since you are trying to communicate with a web server, you should compose HTTP messages.
Replace the line
socket->write("/vt/lyrs=y&x=0&y=0&z=0");
with
socket->write("GET /vt/lyrs=y&x=0&y=0&z=0 HTTP/1.1\r\nHost: mt1.google.com\r\nUser-Agent: TestAgent\r\n\r\n");
And you should get the following response :
HTTP/1.1 200 OK
Date: Sun, 14 Jun 2015 14:24:40 GMT
Expires: Sun, 14 Jun 2015 14:24:40 GMT
Cache-Control: private, max-age=3600
Access-Control-Allow-Origin: *
Content-Type: image/jpeg
X-Content-Type-Options: nosniff
Server: paintfe
Content-Length: 10790
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic,p=0
IMAGEDATA
Parse the response and extract the IMAGEDATA
part.
EDIT : TCP delivers the response divided into chunks. With this approach, you will not be able to receive the whole response since you are trying to receive it in one go.
You should examine the Content-Length
header and wait until receiveing the specified amount of bytes.
Upvotes: 1