I have a multiword String that I'd like to convert to a GET request parameter.
I have an API endpoint /search
that takes in the parameter query
. Now typically your request would look like http://host/search?query=Hello+World
.
I have a String
Hello World that I'd like to convert to this URL encoded parameter.
Ofcourse, I could just write the logic to break it into words and add a +
in between but I was wondering if the URI class could help with this
I'm using Dart's httpClient
to make a request.
Future<String> _getJsonData(String queryToSearch) async {
List data = new List();
var httpClient = new HttpClient();
var request = await httpClient.getUrl(Uri.parse(
config['API_ENDPOINT'] + '/search?query=' +
queryToSearch));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var jsonString = await response.transform(utf8.decoder).join();
data = json.decode(jsonString);
print(data[0]);
return data[0].toString();
} else {
return "{}";
}
}
Essentially, need to encode queryToSearch
as the URL parameter.
A string can be cast to an integer using the int. parse() method in Dart. The method takes a string as an argument and converts it into an integer.
You can use Uri.http(s)
which wrap everythings (query, host, and path) together and encode them accordingly.
final uri = new Uri.http(config['API_ENDPOINT'], '/search', {"query": queryToSearch});
The Uri class provides methods for that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With