here httpserver in java, sends russian string qt application:
public void handle(httpexchange t) throws ioexception { //response server in russian string response = "Ответ от сервера на русском языке"; //"response server in russian" t.sendresponseheaders(200, response.length()); outputstream os = t.getresponsebody(); //os.write(response.getbytes()); //right trying code os.write(response.getbytes(charset.forname("utf-8"))); //and utf-16 //also have tried os.write(charset.forname("utf-16").encode(response).array()); os.close(); }
application in qt gets response server (text in russian)
void mainwindow::response(qnetworkreply *reply) { qbytearray data = reply->readall(); // i've tried // qstring datastring = (qstring)reply->readall(); // qstring dataline = (qstring)reply->readline(); // qstring str= qstring::fromutf8(data); qdebug() << "data server: " << data; label->settext(str); }
i want show normal string in console or in label component, have empty string or array of bytes or sequence of question marks
"\xce\xf2\xe2\xe5\xf2 \xee\xf2 \xf1\xe5\xf0\xe2\xe5\xf0\xe0 \xed\xe0 \xf0\xf3\xf1\xf1\xea\xee\xec \xff\xe7\xfb\xea\xe5"
how can solve problem encoding , convert array qstring , see normal text ?
getbytes
public byte[] getbytes()
encodes string sequence of bytes using platform's default charset, storing result new byte array.
the behavior of method when string cannot encoded in default charset unspecified.
charsetencoder
class should used when more control on encoding process required.
using method serialize string terrible idea; "platform default encoding" depends current locale, operating system , whatnot, while want well-defined encoding transmit data between applications.
in facts, trust when "i've tried everything, nothing works" - that's because string encoded in windows-1251 encoding, happens default 8-bit encoding of windows machine. when try decode on qt side - which, qt5, expects utf-8 default when decoding 8-bit strings, breaks.
first of all, on java side encode string in utf8, making sure specify response length correctly (you have provide number of bytes writing, not of characters in source string):
string response = "Ответ от сервера на русском языке"; //"response server in russian" byte[] response_data = response.getbytes("utf-8"); t.sendresponseheaders(200, response_data.length()); outputstream os = t.getresponsebody(); os.write(response_data); os.close();
then, on qt side, can build qstring
qbytearray
, specifying it's in utf8.
qbytearray data = reply->readall(); qstring str = qstring::fromutf8(data);
(notice may send string in utf-16 or utf-32 well, of course 2 sides must match; chose utf-8 because it's way more common "on wire" format , because it's more compact)
Comments
Post a Comment