Qt, QUrl, QUrlQuery: Encoding special character in a query string - qt

I create a URL query like this:
QString normalize(QString text)
{
text.replace("%", "%25");
text.replace("#", "%40");
text.replace("‘", "%27");
text.replace("&", "%26");
text.replace("“", "%22");
text.replace("’", "%27");
text.replace(",", "%2C");
text.replace(" ", "%20");
return text;
}
QString key = "usermail";
QString value = "aemail#gmail.com";
QUrlQuery qurlqr;
qurlqr.addQueryItem(normalize(key), normalize(value));
QString result = qurlqr.toString();
The result that's be expecting is :
usermail=aemail%40gmail.com.
But I received:
usermail=aemail#gmail.com
I don't know why. Can you help me?
(I'm using Qt5 on Win7)

QUrlQuery's toString by default decodes the percent encoding. If you want the encoded version try:
qurlqr.toString(QUrl::FullyEncoded)
Also you don't need to manually encode the string by replacing characters; you could instead use QUrl::toEncoded() (I suggest you read the QUrlQuery documentation).

Related

Encoding a QString in JSON

I'm trying to encode a QString into a JSON string, so that I can inject it safely via QWebFrame::evaluateJavaScript(QString("o.text = %1;").arg(???)).
For example, in php using the function json_encode
echo json_encode('HELLO "me"');
The output would be
"HELLO \"me\""
This is the internal representation of the string, within the Json object.
In the same way, using Qt, how can I retrieve the internal representation of a string, as it would be encoded as a value, within a Json formatted string?
It's really not that difficult. Start by building up the structure with QJsonObjects
QJsonObject obj;
obj.insert("tag1", QString("Some text"));
Then use QDocument to get a string in Json format
QJsonDocument doc(obj);
QByteArray data = doc.toJson(QJsonDocument::Compact);
QString jsonString(data);
This will produce a string, in the form of: -
{ "tag1" : "Some Text" }
Separate items into a list, splitting on ':'
QStringList items = jsonString.split(':', QString::SkipEmptyParts);
There should be 2 items in the list, the second being the value section of the Json string
"Some Test"}
Remove the final '}'
QString value = items[1].remove('}');
Of-course, you will need to do error checking and be aware that if you have a ':' or '}' in the original string, then you'll need to check for them first.
Original answer doesn't handle : and } inside of string correctly. A similar approach using array which requires only stripping []:
QString encodeJsonStringLiteral(const QString &value)
{
return QString(
QJsonDocument(
QJsonArray() << value
).toJson(QJsonDocument::Compact)
).mid(1).chopped(1);
}
ab"c'd becomes "ab\"c'd"
Or, if you don't need double quotes around the string, replace with .mid(2).chopped(2)

Get a unicode string from a QString in python

I am trying to get a unicode string out of a QString with PySide:
In [63]: qs = QString("órgão")
In [64]: qs
Out[64]: PyQt4.QtCore.QString(u'\xc3\xb3rg\xc3\xa3o')
In [65]: print(unic)
unichr unicode
In [65]: print(unicode(qs))
órgão
But it looks the string comes out different then the original. Why?
I have asked a stupid question again, it should be
QString(u"órgão")
then everything goes ok.

asp.net querystring

I have the following page querystring:
register.aspx?id="jSmith"
I have the following code to retrieve the value of ID
string qString = string.IsNullOrEmpty(Request.QueryString["id"]) ? string.Empty : HttpUtility.UrlDecode(Request.QueryString["id"]);
When I view the value of qString I get something like
"\"jSmith\""
so when I do the following:
if (qString == "jSmith")
{
........
}
it does not not execute the if condition. What do I need to do s that it does not have the quotes.
The code is correct.
The problem is that you are passing to the page "jSmith" with the double quotes as part of the string.
Try invoke the page this way
register.aspx?id=jSmith
That is because the correct way to give the path in this case would be register.aspx?id=jSmith, without the quotes. If you need spaces, or other special characters, in your ID, these should be URL encoded (and will be decoded by your code), but not enclosed in quotes.
For example, if your id was the string john smith, the URL would become register.aspx?id=john+smith, since + is the URL encoding of a space.
You don't need to put quotes around values in querystring, by definition they're all strings...
Your querystring should look like :
register.aspx?id=jSmith
You do not need the quotation marks in your querystring.
It should read
register.aspx?id=jSmith
You should look for
if (qString == "\"jSmith\"")
the \ is escaping the extra "
or you could perform a replace to remove the extra "
use
Response.Redirect("Qstring.aspx?name= smith");
and on the page Qstring.aspx load event
string s=Request.QueryString["name"].ToString();
gives u "smith" in s variable

Newtonsoft.JSON error with text with HTML encoded character

I allow user input from TinyMCE on client and store it as a JSON string, then pass it to server ASP.NET C#.
The JSON String looks like this: { "mcfn2" : ";lt;p;gt;Trước đ& oacute;, việc tung ra t& ecirc;n miền lần đầu ti& ecirc;n được sự đồng & yacute; của ICANN - tổ chức quản l& yacute; t& ecirc;n miền quốc tế" } (JSON string contains Vietnamese accent)
But when process on server, I received error "Unterminated string. Expected delimiter: ". Line 1, position ...." (It looks like the error happened because of đ& oacute;). (In this page, I seperate & with character after it by a space, because it will automacally converted to a Vietnamese if there are no space)
There are no error if user input is English text (no Vietnamese accent).
Please guide me how to fix this error.
I know at this time this will probably not be useful for you, but maybe it can help another person.
You should convert your string to UTF8 to deal with accents (Vietnamese and many other languages) before serializing it to JSON. For that you can use this function:
private string ConvertToUtf8(string textOriginal)
{
if (!string.IsNullOrEmpty(textOriginal))
{
byte[] bytes = Encoding.Default.GetBytes(textOriginal);
return Encoding.UTF8.GetString(bytes);
}
return string.Empty;
}

How do I find out which suffix user has chosen when using a QFileDialog?

Well I'm using the following code to get the filename for a file that needs to be stored ..
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),"/home/user/MyDocs/",tr("JPG files (*.jpg);;BMP files (*.bmp);;PNG files (*.png)"));
I'm providing the user with a number of options regarding the file format in which the file is to be saved. However, the returned QString only gives me the prefix filename the user have chosen, not the suffix and thus I don't know which file format the user chose. How can I detect such a file format?
The code in the question works in Windows (Qt 4.6.2 and Win XP). fileName contains the selected extension. But you are obviously using something else Windows, so you could try this workaround:
QFileDialog dialog(this, tr("Save as ..."), "/home/user/MyDocs/");
dialog.setAcceptMode(QFileDialog::AcceptSave);
QStringList filters;
filters << "JPG files (*.jpg)" << "BMP files (*.bmp)" << "PNG files (*.png)";
dialog.setNameFilters(filters);
if (dialog.exec() == QDialog::Accepted)
{
QString selectedFilter = dialog.selectedNameFilter();
QString fileName = dialog.selectedFiles()[0];
}
That is a slighty modified code from here.
You need to use the 5th optional string
I usually do it like this:
#define JPEG_FILES "JPG files (*.jpg)"
#define BMP_FILES "BMP files (*.bmp)"
#define PNG_FILES "PNG files (*.png)"
QString selectedFilter;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
"/home/user/MyDocs/",
JPEG_FILES ";;" BMP_FILES ";;" PNG_FILES, &selectedFilter);
if (fileName.isNull())
return;
if (selectedFilter == JPEG_FILES) {
...
} else if (selectedFilter == BMP_FILES) {
...
} else if (selectedFilter == PNG_FILES) {
...
} else {
// something strange happened
}
The compiler takes care to concatenate the literal strings in the argument.
I'm not sure how the returned string interacts with tr(). You'll have to test and find out. probably need to un-translate it.
It could have been nicer if the function would return the index of the selected filter but alas, it does not.
A nicer solution would be to put the filters in a list, create a string from it and then compare to the returned selected filter string to the ones in the list. This would also solve the tr() problem.
Have a look to this discussion. It uses QFileInfo on the string that was entered in a QFileDialog.

Resources