Is there a function to do urlencoding in Dart? I am doing a AJAX call using XMLHttpRequest object and I need the url to be url encoded.
I did a search on dartlang.org, but it didn't turn up any results.
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri
Update: There is now support for encode/decode URI in the Dart Uri class
Dart's URI code is placed in a separate library called dart:uri (so it can be shared between both dart:html and dart:io). It looks like it currently does not include a urlencode function so your best alternative, for now, is probably to use this Dart implementation of JavaScript's encodeUriComponent.
Uri.encodeComponent(url); // To encode url
Uri.decodeComponent(encodedUrl); // To decode url
I wrote this small function to convert a Map into a URL encoded string, which may be what you're looking for.
String encodeMap(Map data) {
return data.keys.map((key) => "${Uri.encodeComponent(key)}=${Uri.encodeComponent(data[key])}").join("&");
}
I dont' think there is yet. Check out http://unpythonic.blogspot.com/2011/11/oauth20-and-jsonp-with-dartin-web.html and the encodeComponent method.
Note, it's lacking some characters too, it needs to be expanded. Dart really should have this built in and easy to get to. It may have it in fact, but I didn't find it.
Safe Url Encoding in flutter
Ex.
String url = 'http://example.org/';
String postDataKey = "requestParam="
String postData = 'hdfhghdf+fdfbjdfjjndf'
In Case of get request :
Uri.encodeComponent(url+postDataKey+postData);
In Case of Post Data Request use flutter_inappwebview library
var data = postDataKey + Uri.encodeComponent(postData);
webViewController.postUrl(url: Uri.parse(url), postData: utf8.encode(data));
Uri.encodeComponent() is correct, Uri.encodeFull() has a bug, see below example:
void main() {
print('$text\n');
var coded = Uri.encodeFull(text);
print(coded);
print('\n');
coded = Uri.encodeComponent(text);
print(coded);
}
var text = '#2020-02-29T142022Z_1523651918_RC2EAF9OOHDB_RT.jpg';
Related
Look at this simple source code written in Java:
Uri helpUrl = Uri.parse(getString(R.string.url_help));
try
{
helpUrl = Uri.parse(mainUrl).buildUpon()
.appendPath("xx")
.appendPath("yy")
.appendPath("zzz.html")
.build();
}
catch (Exception ex)
{
//error
}
Note that mainUrl can be provided as http or https and also it may be http://host/xxx or http://host/xxx/. In Java, it will always work. I'm looking for a way to do the same in Dart, but it looks like there's no any buildUpon equivalent. Any advice how to do what I need in Dart? In dart, path has no setter, path segments list has no setter too, so it won't help.
You'll want to use the UriBuilder class which is part of the uri package.
It's usage in your case will look something like this
var ub = UriBuilder.fromUri(Uri.tryParse('https://www.zombo.com/xx'));
ub.path += '/yy';
ub.path += '/zz';
Uri uri = ub.build();
// https://www.zombo.com/xx/yy/zz
There is no automatic management of path separators. It is just string based.
I am trying to get base64 string from image file. When I am using following method
Future convertBase64(file) async{
List<int> imageBytes = fileImage.readAsBytesSync();
String base64Image = await 'data:image/png;base64,' + base64Encode(imageBytes);
// print('length of image bytes ${base64Image.length}');
return base64Image;
}
It shows me an error :
exception---- Converting object to an encodable object failed: Instance of 'Future<dynamic>'
If I use without future it directly pass to next step without converting to base64 String. It usually takes time to convert.
The variable fileImage doesn't seem to match the variable file passed to the function. Might this be the one causing the issue?
I'm curious on why the need to call await on a String - this seems to be unnecessary. The error might be caused on how convertBase64() was called. For async methods like Future<T>, I suggest calling it like:
convertBase64(imageFile).then((String base64Image) {
// Handle base64Image
});
Also, as previously recommended in the comments, it's better to use Uri.dataFromBytes() instead of parsing the encoded String on your own.
Future<String> convertBase64(File file) async{
List<int> imageBytes = file.readAsBytesSync();
return Uri.dataFromBytes(imageBytes, mimeType: "image/png").toString();
}
First check two screen shots. One is debug error one is for json data visual view to give you better understanding. My main goal is to grab only "campaignId" value form this json response. I already tried to use JObject parse but getting error because RestSharp output not json string format so. Now tell me how can i grab that "campaignId" value of json response. Thanks in advance.
static void addEmailToList(string ListName, string Email, string Name)
{
var client = new RestClient("https://api.getresponse.com/v3/campaigns?query[name]="+ListName);
var GetIdreq = new RestRequest(Method.GET);
GetIdreq.AddHeader("X-Auth-Token", "api-key 948df-my-key-7f3c6");
GetIdreq.AddParameter("application/json", ParameterType.RequestBody);
var GetIdres = client.Execute(GetIdreq);
dynamic data = JObject.Parse(GetIdres);
}
You should assign the value of Content of response to your local variable. You can try this.
var GetIdres = client.Execute(GetIdreq).Content;
dynamic data = JObject.Parse(GetIdres);
In Dart I am working on a web game. In this I would need a function where I can get data from the URL, in the same way that you would get it in PHP. How would I do this?
Say I, for example, append the following to my URL when I load my web game: ?id=15&randomNumber=3.14. How can I get them in Dart either as a raw string (preferred) or in some other format?
You can use the Uri class from dart:core
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Uri
ie:
main() {
print(Uri.base.toString()); // http://localhost:8082/game.html?id=15&randomNumber=3.14
print(Uri.base.query); // id=15&randomNumber=3.14
print(Uri.base.queryParameters['randomNumber']); // 3.14
}
import 'dart:html';
void doWork(){
var uri = Uri.dataFromString(window.location.href); //converts string to a uri
Map<String, String> params = uri.queryParameters; // query parameters automatically populated
var param1 = params['param1']; // return value of parameter "param1" from uri
var param2 = params['param2'];
print(jsonEncode(params)); //can use returned parameters to encode as json
}
Import 'dart:html' then you can use window.location...
I created an HTTPService using the Data Centric Development feature in Flash Builder 4. For some reason, I'm not able to set the requestheaders for an HTTP GET request. I've tried setting the headers object for the mx.rpc.http.Operation; but, it doesn't seem to work. Packet sniffers show that the requestheader isn't changed.
For example here's part of the gettour service:
public class GetTourService extends _Super_GetTourService
{
/**
* Override super.init() to provide any initialization customization if needed.
*/
protected override function preInitializeService():void
{
super.preInitializeService();
// Initialization customization goes here
var header:URLRequestHeader = new URLRequestHeader( "Accept", "application/json");
var headers:Array = new Array();
headers.push(header);
var o:Object = this._serviceControl.getOperation( "gettour");
var operation:Operation = o as Operation;
operation.headers = headers;
}
}
However, packet sniffers show the Accept header to be "Accept: /\r\n". In AIR I get a similar problem with the long list of default Accept values and can't set the Accept value to "application/json". What am I missing?
Any help is much appreciated. Thanks!
EDITED: I found the answer this morning. Instead of
headers.push( header);
I used
headers[ "Accept"] = "/application/json";
This worked.
Since the documentation for this is a bit vague I'm going to take a guess. According to the docs, headers is an Object of custom headers, so passing it an indexed array is probably not going to work. Try passing a defined Object instead:
operation.headers = {Accept:"application/json"};