Posted on 02-10-2013
Filed Under (Technology) by bigbang

I tried to write a simple http server using Qt as a desktop tool. But when I tried to handle Chinese characters in UTF-8 encoding, my Firefox will always get mess characters.

The reason must be the difference between QString encoding and http encoding. I have encoded the http content using UTF-8, and I also should do something for QString.

Finally, I find the steps to let this simple http server handle Chinese characters.

First, in main function of your program, using following code to set global QString handler:

QTextCodec *codec = QTextCodec::codecForLocale();
QTextCodec::setCodecForTr(codec);

Second, when you get http request, process the request and generate the feedback of the http request, you can send the content by following code using UTF-8:

//generate html content according to http request
//which is result
...
QString content = tr("HTTP/1.0 200 Ok\r\n"
                                "Content-Type: text/html; charset=\"utf-8\"\r\n"
                                "\r\n");
content = content + result;

QTcpSocket* socket = (QTcpSocket*)sender();
QTextStream os(socket);
os.setCodec("UTF-8");
os.setAutoDetectUnicode(true);
os << content;

Then you will get the right output in you web browser.

© 2013, The Big Bang on Reading Busy. All rights reserved.
On republishing this post you must provide link to the original post.

Post a Comment
Name:
Email:
Website:
Comments: