Let Qt Http Server to Support UTF-8 Characters
Contents
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.
Author Watterry
LastMod 2013-10-02