8 using namespace stefanfrings;
22 Q_ASSERT(sentHeaders==
false);
23 headers.insert(name,value);
28 Q_ASSERT(sentHeaders==
false);
29 headers.insert(name,QByteArray::number(value));
39 this->statusCode=statusCode;
40 statusText=description;
45 return this->statusCode;
48 void HttpResponse::writeHeaders()
50 Q_ASSERT(sentHeaders==
false);
52 buffer.append(
"HTTP/1.1 ");
53 buffer.append(QByteArray::number(statusCode));
55 buffer.append(statusText);
56 buffer.append(
"\r\n");
57 foreach(QByteArray name, headers.keys())
61 buffer.append(headers.value(name));
62 buffer.append(
"\r\n");
66 buffer.append(
"Set-Cookie: ");
68 buffer.append(
"\r\n");
70 buffer.append(
"\r\n");
71 writeToSocket(buffer);
76 bool HttpResponse::writeToSocket(QByteArray data)
78 int remaining=data.size();
79 char* ptr=data.data();
80 while (socket->isOpen() && remaining>0)
83 if (socket->bytesToWrite()>16384)
85 socket->waitForBytesWritten(-1);
88 qint64 written=socket->write(ptr,remaining);
101 Q_ASSERT(sentLastPart==
false);
104 if (sentHeaders==
false)
111 headers.insert(
"Content-Length",QByteArray::number(data.size()));
117 QByteArray connectionValue=headers.value(
"Connection",headers.value(
"connection"));
118 bool connectionClose=QString::compare(connectionValue,
"close",Qt::CaseInsensitive)==0;
119 if (!connectionClose)
121 headers.insert(
"Transfer-Encoding",
"chunked");
136 QByteArray size=QByteArray::number(data.size(),16);
138 writeToSocket(
"\r\n");
140 writeToSocket(
"\r\n");
154 writeToSocket(
"0\r\n\r\n");
170 Q_ASSERT(sentHeaders==
false);
171 if (!cookie.
getName().isEmpty())
173 cookies.insert(cookie.
getName(),cookie);
188 write(
"Redirect",
true);
200 return socket->isOpen();
HTTP cookie as defined in RFC 2109.
QByteArray getName() const
Get the name of this cookie.
QByteArray toByteArray() const
Convert this cookie to a string that may be used in a Set-Cookie header.
bool hasSentLastPart() const
Indicates whether the body has been sent completely (write() has been called with lastPart=true).
void flush()
Flush the output buffer (of the underlying socket).
bool isConnected() const
May be used to check whether the connection to the web client has been lost.
void setHeader(const QByteArray name, const QByteArray value)
Set a HTTP response header.
QMap< QByteArray, HttpCookie > & getCookies()
Get the map of cookies.
int getStatusCode() const
Return the status code.
void setStatus(const int statusCode, const QByteArray description=QByteArray())
Set status code and description.
HttpResponse(QTcpSocket *socket)
Constructor.
void write(const QByteArray data, const bool lastPart=false)
Write body data to the socket.
QMap< QByteArray, QByteArray > & getHeaders()
Get the map of HTTP response headers.
void setCookie(const HttpCookie &cookie)
Set a cookie.
void redirect(const QByteArray &url)
Send a redirect response to the browser.