Question

I am writing a piece of software that uses Qt/KDE libs. The objective is to parse the HTTP header response fields into different fields of a struct. So far the HTTP header response is contained in a QString.

It looks something like this:

"HTTP/1.1 302 Found
date: Tue, 05 Jun 2012 07:40:16 GMT
server: Apache/2.2.22 (Linux/SUSE)
x-prefix: 49.244.80.0/21
x-as: 23752
x-mirrorbrain-mirror: mirror.averse.net
x-mirrorbrain-realm: region
link: <http://download.services.openoffice.org/files/du.list.meta4>; rel=describedby; type="application/metalink4+xml"
link: <http://download.services.openoffice.org/files/du.list.torrent>; rel=describedby; type="application/x-bittorrent"
link: <http://mirror.averse.net/openoffice/du.list>; rel=duplicate; pri=1; geo=sg
link: <http://ftp.isu.edu.tw/pub/OpenOffice/du.list>; rel=duplicate; pri=2; geo=tw
link: <http://ftp.twaren.net/OpenOffice/du.list>; rel=duplicate; pri=3; geo=tw
link: <http://mirror.yongbok.net/openoffice/du.list>; rel=duplicate; pri=4; geo=kr
link: <http://ftp.kaist.ac.kr/openoffice/du.list>; rel=duplicate; pri=5; geo=kr
digest: MD5=b+zfBEizuD8eXZUTWJ47xg==
digest: SHA=A5zw6PkywlhiPlFfjca+gqIGLHA=
digest: SHA-256=HOrd0MMBzS8Ctljpe4PauwStijsnBKaa3gXO4L30eiA=
location: http://mirror.averse.net/openoffice/du.list
content-length: 329
connection: close
content-type: text/html; charset=iso-8859-1" 

In addition to the custom fields there might be few more fields in the header response. The only possible way that I came up was to manually search for the fields like "link", "digest" and others and create a QMap with the fields as keys.However, I guess there must be a better way to do this. I would be thankful to you if you could help me.

Was it helpful?

Solution

The HTTP header should initially be in a QByteArray (because it is in ASCII, not UTF-16), but the method would be the same with a QString:

  • split the header line by line,
  • split each line at the colon character,
  • trim any white spaces (regular spaces and '\r' characters) around the 2 resulting strings before storing them.
QByteArray httpHeaders = ...;
QMap<QByteArray, QByteArray> headers;

// Discard the first line
httpHeaders = httpHeaders.mid(httpHeaders.indexOf('\n') + 1).trimmed();

foreach(QByteArray line, httpHeaders.split('\n')) {
    int colon = line.indexOf(':');
    QByteArray headerName = line.left(colon).trimmed();
    QByteArray headerValue = line.mid(colon + 1).trimmed();

    headers.insertMulti(headerName, headerValue);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top