I'm making a call using Dio that send some query parameters, using map constructor
response = await Dio().get(url, queryParameters: {
"apikey": publicKey,
"hash": hash,
"ts": timestamp,
"nameStartsWith": searchTerm
});
Everything works correctly, but when try to send a int value, Dio throw a error
response = await Dio().get(url, queryParameters: {
"apikey": publicKey,
"hash": hash,
"ts": timestamp,
"nameStartsWith": searchTerm,
"page" : 10
});
type 'int' is not a subtype of type 'Iterable < dynamic > '#0
And i can't just convert the int value to string, because api is expcting int type.
Any help ?
There is no such thing as an int type in an URL and therefore in query parameters.
An URL can only be a String.
Just convert it to String and be done.
Related
In Twilio Studio, I'm making a GET request and am trying to parse JSON and subsequently assign variables based on the parsed JSON. I'm having difficulty doing so with the JSON that is returned.
Essentially I'm trying to set variables from the "Row" that matches the returned JSON (a user dials in, enters their PIN {{widgets.PIN_Entry.Digits}}, the PIN will match a "Row" in the returned JSON from the GET request and we set variables for userID, userEmail, userName, userPin for the matched row).
{
"DataSource": {
"Id": "12345",
"Name": "Dial-In Subscribers",
"Rows": [
[
"EMP-0226",
"ron#pawneeil.com",
"Ron Swanson",
"00054321"
],
[
"EMP-0267",
"leslie#pawneeil.com",
"Leslie Knope",
"00012345"
]
],
"TotalRows": 2,
"LastUpdated": "2020-08-26T03:39:42.7670000Z",
"CompanyId": 12345
}
}
I can easily do this with JSON Path (not supported by Twilio studio) to select the values I'm looking to set as variables, but I can't figure out how to use Liquid to do this.
userID == $.DataSource.Rows[?(#.includes('00012345'))].[0]
(would return "EMP-0267")
userEmail == $.DataSource.Rows[?(#.includes('00012345'))].[1]
(would return "leslie#pawneeil.com")
userName == $.DataSource.Rows[?(#.includes('00012345'))].[2]
(would return "Leslie Knope)
userPin == $.DataSource.Rows[?(#.includes('00012345'))].[3]
(would return "00012345")
Can anyone share some ideas on how to parse the JSON and set variables using Liquid? Here's how I'm thinking I would accomplish this:
Match the variable {{widgets.PIN_Entry.Digits}} to a row in the returned JSON
Parse the selected row and set variables for userID, userEmail, userName, userPin.
I use the Run Function Widget in these cases, I find it much easier to deal with then the nuances of Liquid Syntax.
// Description
// Make a read request to an external API
// Add axios 0.20.0 as a dependency under Functions Settings, Dependencies
const axios = require('axios');
exports.handler = function (context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
// Arrays start at 0
let selectedDigit = 0;
axios
.get(`https://x.x.x.x/myAPI`)
.then((response) => {
let { Rows } = response.data.DataSource;
let result = Rows.filter((record, index) => index === selectedDigit);
twiml.say(`The result is ${result}`);
return callback(null, twiml);
})
.catch((error) => {
console.log(error);
return callback(error);
});
};
I have to check json response if it contains needed types. What do I mean:
{
"success": {
"anonym_id": 11156,
"has_empty_profile": false,
"token": "4690e404-cfec-4918-b555-2f0d84675eee",
"twins": [],
"uid": 7380
}
}
So I have to check that "anonym_id" is int(not a specific number like here 11156, but just int), "has_empty_profile" is boolean, "token" is string etc.
How to do that with rest assured?
Best way to do this is
JsonPath js1 = new JsonPath(new File(
"Your Json I stored in a file"));
assertTrue(js1.get("success.findAll {anonym_id -> anonym_id=11156}.has_empty_profile") instanceof Boolean);
assertTrue(js1.get("success.findAll {anonym_id -> anonym_id=11156}.token") instanceof String);
I am writing a Flutter/Dart application and am getting a JWT back from an auth server that has some claims I need to use. I have looked at various (4 so far) Dart JWT libraries -- but all are either too old and no longer work with Dart 2, etc. or they need the secret to decode the JWT which makes no sense and isn't correct (or possible since I have no access ).
So -- how can one get a JWT and get the claims from it within a "modern" Dart/Flutter application?
JWT tokens are just base64 encoded JSON strings (3 of them, separated by dots):
import 'dart:convert';
Map<String, dynamic> parseJwt(String token) {
final parts = token.split('.');
if (parts.length != 3) {
throw Exception('invalid token');
}
final payload = _decodeBase64(parts[1]);
final payloadMap = json.decode(payload);
if (payloadMap is! Map<String, dynamic>) {
throw Exception('invalid payload');
}
return payloadMap;
}
String _decodeBase64(String str) {
String output = str.replaceAll('-', '+').replaceAll('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw Exception('Illegal base64url string!"');
}
return utf8.decode(base64Url.decode(output));
}
Use 'base64Url.normalize()' function.
That's what _decodeBase64() does from the answer above!
String getJsonFromJWT(String splittedToken){
String normalizedSource = base64Url.normalize(encodedStr);
return utf8.decode(base64Url.decode(normalizedSource));
}
As of this writing, the jaguar_jwt package is being actively maintained. Although it is not clearly documented, it does have a public method that will decode Base64Url encoding. It does basically the same thing as the accepted answer.
//import 'package:jaguar_jwt/jaguar_jwt.dart';
final String token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTQ4MjAxNjIsImlhdCI6MTU1NDc3Njk2MiwiaXNzIjoiU3VyYWdjaCIsInN1YiI6IjQifQ.bg5B_k9WCmxiu2epuZo_Tpt_KZC4N9ve_2GEdrulcXM';
final parts = token.split('.');
final payload = parts[1];
final String decoded = B64urlEncRfc7515.decodeUtf8(payload);
This gives a JSON string, which for this particular example is:
{
"exp":1554820162,
"iat":1554776962,
"iss":"Suragch",
"sub":"4"
}
See also:
JWT: The Complete Guide to JSON Web Tokens
String based data encoding: Base64 vs Base64url
you can use jwt_decoder package to decode and/or check if you token is expired
//to get claims from your token
main () {
String yourToken = "Your JWT";
Map<String, dynamic> decodedToken =
JwtDecoder.decode(yourToken);
/*
If the token has a valid format, you will get a
Map<String,dynamic> Your decoded token can look like:
{
"sub": "1234567890",
"name": "Gustavo",
"iat": 1516239022,
"exp": 1516239022,
"randomKey": "something else"
}
*/
}
//check if your token is expired
main () {
String yourToken = "Your JWT";
bool hasExpired = JwtDecoder.isExpired(yourToken);
// You will get a true / false response
// true: if the token is already expired
// false: if the token is not expired
}
you can get your token expiration date using
main () {
String yourToken = "Your JWT";
DateTime expirationDate = JwtDecoder.getExpirationDate(token);
// 2025-01-13 13:04:18.000
print(expirationDate);
}
you can also find out how old your token is
// Token payload must include an 'iat' field
main () {
String yourToken = "Your JWT";
Duration tokenTime = JwtDecoder.getTokenTime(token);
// 15
print(tokenTime.inDays);
}
to learn more about what JWT Decoder can do, visit their package documentation page
you can decode JWT base64 by seperate first part of it that contains "."
String decodeUserData(String code) {
String normalizedSource = base64Url.normalize(code.split(".")[1]);
return utf8.decode(base64Url.decode(normalizedSource));
}
I attempted to update a JSON at myjson.com, using the WebRequest(), resulting in a failure.
return result: 2018.05.22 23:54:44.401 webreq NZDCAD,H1: Status code: 404, error: 4000
I want to change name from "John" to "Labu"
My code is like the following:
void postJson()
{
char post[], result[];
string headers = "Content-Type: application/json\r\n";
string obj = "'data:{\"name\":\"Labu\"}'";
StringToCharArray( obj, post, 0, WHOLE_ARRAY ); // Must specify string length;
// otherwise array has
// terminating null character in it
int res = WebRequest( "POST",
"https://api.myjson.com/bins/tj8e2",
"PUT",
NULL,
10000,
post,
ArraySize( post ),
result,
headers
);
Print( "Status code: " , res, ", error: ", GetLastError() );
Print( "Server response: ", CharArrayToString( result ) );
}
string obj="'data:{\"name\":\"Labu\"}'";
you do not need the '-chars
you must make sure that the address is valid and that it is added to the list of allowed web sites ( inside the MetaTrader Terminal configuration setup panel ).
remove POST and put PUT,
read your own code: WebRequest( "POST",
should be, WebRequest( "PUT",
You are using POST method still.
Here:
int WebRequest(
const string method, // HTTP method
const string url, // URL
const string cookie, // cookie
const string referer, // referer
int timeout, // timeout
const char &data[], // the array of the HTTP message body
int data_size, // data[] array size in bytes
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
Now would be a good time to also mention mt4 don't support PUT or DELETE only POST and GET ;)
Problem Specification:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
The above parameters should be passed to the system as a row HTTP POST in a JSON string.
I am trying to solve this problem using RESTSharp. But I am having some problem Like after executing the request my code return a Null response and I am not sure my JSON string is passing properly or not.
Here is my Code:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", #"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
Is there anything wrong with my code??
And I am little bit confused about
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
Basically I want to know how to utilize AdduUrlSegment() and AddParameter().
Thanks in advance.
For using request.AddUrlSegment("username", "Admin") you should define your url template properly: var request = new RestRequest("api/employee/{username} ", Method.POST);
Also you should set Content-Type
request.AddHeader("Content-Type", #"application/json");
befor adding a Body