Using Flutter/Dart- i'd like to make a Uri network call with queryParameters that include arrays.
Ex:
Map<String, dynamic> queryParameters = {
'include': 'messages',
'scopes': ['withHasUnreadMessages', 'withSubscriberUserIds'],
};
uri = Uri.https(_getBaseUrl(), '/mypath', queryParameters);
Which prints:
https://mypath?include=subscribers&scopes=withHasUnreadMessages&scopes=withSubscriberUserIds
However, my api server (PHP) doesn't play nicely with requests that include duplicate keys. My server wants:
https://mypath?include=subscribers&scopes[]=withHasUnreadMessages&scopes[]=withSubscriberUserIds
Is there a way to add brackets to darts Uri queryParameters?
PS - This might have been a comment https://stackoverflow.com/a/57367680/6010500 but i don't have the reputation points.
Not a dart user, but from first glance, you can add the array brackets to the input name
Map<String, dynamic> queryParameters = {
'include': 'messages',
'scopes[]': ['withHasUnreadMessages', 'withSubscriberUserIds'],
};
uri = Uri.https(_getBaseUrl(), '/mypath', queryParameters);
Related
Fetch is adding local host and IP address of the Vue app in front of the url when I include a variable for a project ID in API request. If the projectId is hard coded the endpoint works. How do I eliminate the local part of the url?
I have tried to add the variable as ${projectId} or be concatenation + projectId + the result is the same. The url sent looks like
const projectId = ref('')
const uri = `"https://developer.api.autodesk.com/bim360/admin/v1/projects/b.${ projectId.value}/users"`
function getUsers() {
fetch
(uri, requestOptions)
.then(response => response.json())
.then((response) => {
res.value = response
})
.catch(error => console.log('error', error))
}
Looking in the network the url that is sent looks like this
http://127.0.0.1:5173/"https://developer.api.autodesk.com/bim360/admin/v1/projects/b.bfca3830-79e5-45c3-8ebe-0c3ba17273eb/users"
Not a real projectID by the way.
Thanks for any suggestions!
It looks like you're using extra quotations (""). When you're using string interpolation you don't need to use quotations (""). Declare your URI like example given bellow.
const uri = `https://developer.api.autodesk.com/bim360/admin/v1/projects/b.${ projectId.value}/users`
I need to send POST request from my UWP app.
I read about it here.
I use one shared HttpClient.
private Windows.Web.Http.HttpClient httpClient;
Initialization:
httpClient = new Windows.Web.Http.HttpClient();
var headers = httpClient.DefaultRequestHeaders;
string header = "Chrome/64.0.3282.140";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
I use this object for all request
But when I use it for POST request, it works like GET request or POST, but without parameters
Uri requestUri = new Uri("http://some_websit.ru");
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("par1", "val1");
pairs.Add("par2", "val2");
HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs)
var result = await httpClient.PostAsync(requestUri, formContent);
string resultContent = await result.Content.ReadAsStringAsync();
It ignore parameters which I give.
I tried to send POST request here http://seriyps.ru/postget/ and it works.
There is nothing wrong with your code, I have tested it locally with the same code, only a different URL, and the POST request is sent properly along with the passed in parameters:
I recommend you to install Telerik Fiddler 4 to see the network traffic and confirm that the parameters are indeed sent. I have used http://example.com just as a sample URL here. I would suspect the problem is rather on the side of the server than your app or that the server expect different parameters than what is being sent.
I have developed a REST API using feathers.js (https://feathersjs.com/).
When trying to do a HTTP 'read' request in Flutter using package:http/http.dart I have encountered an error. The http.dart library is unable to correctly parse the query params I pass to the URI.
The error I receive through the Android Studio debug console is ;
FormatException: Invalid character (at character 84) E/flutter
(11338): ...lk.com/weatherobs?last=true&location[$in]=Bellambi&location[$in]=Nowra ....
The error is indicating the square brackets and possibly the $ sign ('[$in]' ) are the issue.
_getDemoRequest() {
String url = r"http://demoapi.ap-southeast-2.elasticbeanstalk.com/weatherobs?last=true&location[$in]=Bellambi&location[$in]=Nowra&location[$in]=Sydney Airport&location[$in]=Thredbo Top Station&location[$in]=Hobart&location[$in]=Coolangatta";
http.read(url).then(print);
}
In the URL I have tried prefixing the String with and without 'r' for a raw string to no avail.
I have also tried using httpClient with params with no success and the exact same error on the square brackets eg '[$in]'
String httpbaseUri = "http://xxxx.ap-southeast-2.elasticbeanstalk.com";
String qParams = r"?last=true&location[$in]=Bellambi&location[$in]=Nowra";
String path = "/weatherobs";
var _uri = new Uri.http(baseUri, path, qParams);
await httpClient.read(_uri, headers: {"Accept": "application/json"});
As a person with approximately 3 weeks of Flutter/Dart experience I believe its an elementary problem, but one in which several hours of research has uncovered no solution.
The ways the URI query parameters are structured (with the square brackets ie [$in]) are dictated by the feathers.js framework.
Any help would be appreciated.
It has been brought to my attention in another thread https://stackoverflow.com/questions/40568/are-square-brackets-permitted-in-urls :
That the URL Specification RFC 3986 generally does not permit square brackets in an URL.
My question was triggered as the get request works as intended in Postman, Chrome Browser and also javascript applications using axios.js, but not in an application developed in Flutter/Dart using standard http.read methods.
It doesn't look like [] are supported in the URL (except for the host IP for IPv6). See Are square brackets permitted in URLs?.
Please check if the API accepts them when they are encoded like:
void main() {
var url = r'http://demoapi.ap-southeast-2.elasticbeanstalk.com/weatherobs';
var locationKey = Uri.encodeQueryComponent(r'location[$in]');
var qParams = 'last=true&$locationKey=Bellambi&$locationKey=Nowra&$locationKey=Sydney Airport&$locationKey=Thredbo Top Station&$locationKey=Hobart&$locationKey=Coolangatta';
try {
print(Uri.parse(url).replace(query: qParams));
} catch(e) {
print(e);
}
}
DartPad example
See also api.dartlang.org/stable/1.24.3/dart-core/Uri/…
You can use this flutter package which allow you to communicate with your feathers js server from flutter app as said in: https://stackoverflow.com/a/65538226/12461921
I'm writing some functional tests for a Grails controller, and I feel it's getting messy when testing the query parameters.
I know that I can do this, but it just seems clunky.
Map getParms = [id:1, x:foo, y:bar, z:baz]
RestResponse response = builder.get("http://example.com/api/{id}?x={x}&y={y}&z={z}") {
urlVariables getParams
}
Ideally I'd like to:
Fill the base URL (i.e. the Id) using the urlVariables argument above
Pass another map of query params that appends each as a key value pair
Something like:
Map queryParms = [x:foo, y:bar, z:baz]
RestResponse response = builder.get("http://example.com/api/{id}") {
urlVariables id:1
queryVariables queryParams
}
I feel this would be much more 'DRY', and easier to read/write.
Does anyone know if such a mechanism exists? I know I could put together a class to do it, but I was hoping to avoid this if there is an existing implementation.
You can do as below.
Map queryParams = [x: 'foo', y: 'bar', z: 'baz']
RestResponse response = builder.get("http://example.com/api/{id}", queryParams) {
urlVariables id:1
}
RestBuilder's get() is overloaded to accept three params: String url, Map queryParams and the RequestCustomizer closure
I felt the same awkwardness when initially using the API. Currently I'm doing something slightly more concise:
RestResponse response = builder.get("http://example.com/api/{id}?x={x}&y={y}", [id:1, x:'foo', y:'bar'])
It doesn't feel that bad, kinda same style with named sql parameters in groovy SQL
I am trying to get my Actionscript program to turn in a key-value (more specifically: a key, value1, value2) object into a server. I am doing the html request properly, but I'm not sure what kind of object to send; can anyone help?
--Thanks
When I understand correctly you want to post an object to the server, which has 1 key and multiple values. The latter is not supported by a HTTP_POST/GET call, you could however use something as AMF to send a VO from Flash over to a server and decode the AMF object on the server. Not sure whether or not that is where you are looking for, or you just want to post 2 values to a server.
Posting 2 values to a server is simple, but it requires two keys.
public function URLVariablesExample() {
var url:String = "http://www.domain.com/script.php";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
variables.keyOne = new Date().getTime();
variables.keyTwo = "Something";
request.data = variables;
navigateToURL(request);
}