Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode URLs in Dart?

I'm trying to port some code from Python to Dart (for a Flutter application). However, I'm having a bit of trouble encoding URLs. I'm trying to do the equivalent of parsedData = urllib.parse.quote(STR_DATA). The closest I've gotten is with the Uri Dart class, with:

parsedData = Uri(queryParameters: STR_DATA);
parsedData = Uri.encodeComponent(parsedData.toString());

This gets close to what I'm trying to get but not quite. The result I get using Python is something like this (side note: it's only encoding after the period):

ig_sig_key_version=4&signed_body=efbcf4ac8577da5eb43f33f369cda4248dba52a407e88a565038b53933737bba.%7B%22phone_id%22%3A%20%22ee79227a-cf89-41c8-9598-d0c6f3931fa4%22%2C%20%22_csrftoken%22%3A%20%22BB1PRXVV1y6FgU0Rfmcda3jJG5eVFSPd%22%2C%20%22username%22%3A%20%22USERNAME%22%2C%20%22guid%22%3A%20%22c668814c-a1e9-487c-97f0-8491b2c07c1c%22%2C%20%22device_id%22%3A%20%22android-7eb57ab90e1e2c3e%22%2C%20%22password%22%3A%20%22PASSWORD%22%2C%20%22login_attempt_count%22%3A%20%220%22%7D

While with Dart, I get something like this:

ig_sig_key_version=4&signed_body=d1c26c132b536b3f4ffdd7f5c0524503e48216fb7f638b5f4cab65d74a9834de.%3Fphone_id%3D112626ab-1946-4ad0-bc63-b233f57033f9%26_csrftoken%3DhiPh0jSvjd0eP2dP4VUr83t3htYF7xci%26username%3DUSERNAME%26guid%3D999d2242-f52a-4044-96d9-2245c6757fbc%26device_id%3Dandroid-5daff5c3029f414c%26password%3DPASSWORD%26login_attempt_count%3D0

By the way, the reason why I need this to encode in the same way is because otherwise my HTTP request returns 400. Anyway, any help is appreciated; thank you in advance.

OTHER SIDE NOTE: I think this is what's causing my request to be rejected but I don't know, I haven't done a lot of web stuff. If you think it might be something else, feel free to correct me.

like image 746
Fabio Suarez Avatar asked Jan 08 '20 05:01

Fabio Suarez


2 Answers

You are doing too much. In this case, you only need to do: parsedData = Uri.encodeComponent(STR_DATA); to get the same result as the Python code.

like image 177
lrn Avatar answered Nov 19 '22 07:11

lrn


Use Dart Uri Class

var uri = 'http://example.com/path/to/page?name=ferret john';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.com/path/to/page?name=ferret%20john');

var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
like image 32
Krishnadas P Avatar answered Nov 19 '22 05:11

Krishnadas P