How to remove quotation and symbols while decoding from JSON value? Flutter - flutter

This is the code to get my auth token.
Future <String> getToken() async{
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('token');
}
When i print the token it gives me this json value with double quotation mark.
I/flutter (14710): "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiZDQzZjFjNWZjZDQxYjIzYzllNGU2ZWIyZjQ1M2FmZDgwOTJiNGZmNDAyYjI0OTBmM2RiYTUzMTgzYTU2ODZjNTNiNzVmMDY3ZmIzMmNjMjUiLCJpYXQiOjE1OTA0MDg2NjksIm5iZiI6MTU5MDQwODY2OSwiZXhwIjoxNjIxOTQ0NjY5LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.3YYdR8P1_XzK--VLAwT5gxmkyLZPMuvQhzQQ5OOl_nv0jriPwFY9sqHdL_wiqpAA5vtgBOnyAwZ2kSI_BgDzsKZzY2vMVa47Tyuz87uEFZ7-aHYvNY_r4T_gIkwAuLwc8qN2kuytFjEtuq-iQUiWgEzp5y2n3BDlzXZ7rZi5Xp1_y_6_ysII9RQtX37LuDFt3AIRbYLGDBAilPHi0iJB_jQqWqH8J1mUzCsArj2VuSel7kERqpwFz-SwOOS4EA7CaoOuOlleOpynBalTK9vm1vU3n81K4TAgNq-Mg9CsiFMVQULURdmku7-2gcc3VS8vBXo9OlEgzqmGjLDvIy8_-LCcwuoSVC2DL2t2PIcNUDKQsBu1GBPQ99wzHcnyEpvjVRkg7v4zQWtlIUY6PcLjNf_vnfuXuCERAwBwjS86T7n8ZscfmVVebISVvAKyDN6YhW41hnUw-AZYRLtuhbE8Z48V0tLfLw9aeVr-Qe2mlaYj0LqGYlqBLqUtRl9HSaA9USa6tQ1KQJvF5_6JPcIBJuSkEsrY9n1xhnCViAiyFVF4XWbtToULn69B2UtoXw1X8y_Wek_T7D7t0fi5KWKj8QHO6yI3ZIWViERS2K6n7mnL_3z_7CNeewVxmqMXNdeWl7yPmAMzUAv6z7pWm-R1Qpv7tNVj4-FfQAk3vOm56hE"
This is how i used the token you get the post from api but it isnt working.
Future<Model> ViewWelcomeScreen() async {
String url = '$baseurl/post/20';
ApiService().getToken().then((value){
token = value;
});
final response = await http.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
print(token);
if (response.statusCode == 200) {
var test = json.decode(response.body);
var jsonResponse = test['data'];
return Model.fromJson(jsonResponse);
} else {
throw Exception('Failed to load data');
}
}

Future<Model> ViewWelcomeScreen() async {
String url = '$baseurl/post/20';
ApiService().getToken().then((value){
token = value;
});
final response = await http.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
print(token);
if (response.statusCode == 200) {
var test = json.decode(response.body);
var jsonResponse = test['data'];
return Model.fromJson(jsonResponse);
} else {
throw Exception('Failed to load data');
}
}
code is wrong in a way, think you have async and then both on the same function, why?
ApiService().getToken().then((value){
token = value;
});
here you're saying I want token and I don't need to be awaited then you go and try to use that variable
final response = await http.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
see in flutter every async-await works like event loop in javascript
I write async
normal code
using then in 1. function
dependent code in 1. as async-await
what will be the output?
event loop will be having 1,2,3,4 as async functions
first, it will run 1 and as soon as it receives normal code it runs normally but if it receives then it will understand that this result is not important so let me do rest of the work and will come back to execute 3rd then function so it will run 4 and then 3rd function
but you want token so
ApiService().getToken().then((value){
token = value;
});
replace this to
token = await ApiService().getToken();
your service might need token and that's the reason it's not 200 status code.

If you just want to remove the "" from the string, then just use the replaceAll method
String string = '"foo"';
//Output: 'foo'
string.replaceAll('"', '');

Related

Can't get auth token stored in flutter secure storage to headers

I am making flutter app using API and I have a problem. When I want to get auth token to make request, flutter says that "Expected a value of type 'String', but got one of type '_Future'". How can I make a request with auth token without that error?
My login function, where I write the token:
loginUser() async {
final storage = new FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/login");
await http
.post(uri,
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"username": emailController.text,
"password": passwordController.text
}))
.then((response) async {
if (response.statusCode == 200) {
var data = json.decode(response.body);
await storage.write(key: "token", value: data["token"]);
print(data["token"]);
} else {
print(json.decode(response.body));
}
});
}
My getdata function, where i use the token:
getdata() async {
final storage = FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
await http.get(uri, headers: {
"Content-Type": "application/json",
"Authorization": await storage.read(key: "token")
});
}
try this code
String token = await storage.read(key: 'token');
//make sure if there is no Bearer just token in that case just pass the token
var headers = {
'accept': 'application/json',
'Authorization': 'Bearer ${token}',
};
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
Response response = await http.get(
uri,
headers: headers
);
print (response);

When I use flutter http library with headers authorization token, its shows 500, in console. but in postman all okay

Here is my code, I also tried using retrofit but I failed and it shows 500 and "message": "Undefined index: token". but in postman, it shows 200. how can it be possible?
Also tried
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
Future getCertificateList() async {
final url = Uri.parse(
'https://portal-api.jomakhata.com/api/getCertificateList');
final response = await http.get(url,
headers: {
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiY',
},
);
print(response.statusCode);
print(response.body);
return response.body;
}
In my console it's print 500
this is postman request image
try this code:
Future getCertificateList() async {
final uri = Uri.https('https://portal-api.jomakhata.com','/api/getCertificateList');
final response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader:
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiYv',
HttpHeaders.contentTypeHeader: 'application/json',
});
print(response.statusCode);
print(response.body);
return response.body;
}

Google Drive API: Uploading and creating folders with http requests, for example in DIO with Flutter

I'm trying to create a simple Flutter app which interacts with the Google Drive API.
Authentication works great via the Google Sign In package, so I have access to the correct headers and auth tokens.
What I don't understand however, despite trying different approaches and reading the Drive Documentation up and down - how can I interact with the API via http requests, for example via Dio or via the "standard" way in dart/flutter?
To state one example: I want to upload an an image the user picked. I have everything figured out (the file path, the auth token, etc.), but how does a http request look like?
Here is the "bare" http request:
Map headers = await user.currentUser.authHeaders;
var formData = FormData.fromMap({
'name': filePath,
'file': MultipartFile.fromBytes(fileData, filename: filePath)
});
var response = await Dio().post(
'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
data: formData,
options: Options(headers: headers));
print(response);
It's probably a very mundane/trivial question, but I just can't figure it out ..
Thanks in advance for your help!
Christian
You need to create the File first then upload the file data into it.
I'll using the http plugin and not DIO. But the same process should work for dio.
Step one: Create the file metadata in a folder
Future<String> createFile({File image, String folderId}) async {
String accessToken = await Prefs.getToken();
Map body = {
'name': 'name.jpg',
'description': 'Newly created file',
'mimeType': 'application/octet-stream',
'parents': ['$folderId']
};
var res = await http.post(
'https://www.googleapis.com/drive/v3/files',
headers: {
'Authorization': 'Bearer $accessToken',
'Content-Type': 'application/json; charset=UTF-8'
},
body: jsonEncode(body),
);
if (res.statusCode == 200) {
// Extract the ID of the file we just created so we
// can upload file data into it
String fileId = jsonDecode(res.body)['id'];
// Upload the content into the empty file
await uploadImageToFile(image, fileId);
// Get file (downloadable) link and use it for anything
String link = await getFileLink(fileId);
return link;
} else {
Map json = jsonDecode(res.body);
throw ('${json['error']['message']}');
}
}
Step two: Upload image data into empty file
Future uploadImageToFile(File image, String id) async {
String accessToken = await Prefs.getToken();
String mimeType = mime(basename(image.path).toLowerCase());
print(mimeType);
var res = await http.patch(
'https://www.googleapis.com/upload/drive/v3/files/$id?uploadType=media',
body: image.readAsBytesSync(),
headers: {
'Authorization': 'Bearer $accessToken',
'Content-Type': '$mimeType'
},
);
if (res.statusCode == 200) {
return res.body;
} else {
Map json = jsonDecode(res.body);
throw ('${json['error']['message']}');
}
}
Step three: Get downloadable file link(to store in database or use for anything)
Future getFileLink(String id) async {
String accessToken = await Prefs.getToken();
var res = await http.get(
'https://www.googleapis.com/drive/v3/files/$id?fields=webContentLink',
headers: {
'Authorization': 'Bearer $accessToken',
'Content-Type': 'application/json; charset=UTF-8'
},
);
if (res.statusCode == 200) {
Map json = jsonDecode(res.body);
String link = json['webContentLink'];
return link.split('&')[0];
} else {
Map json = jsonDecode(res.body);
throw ('${json['error']['message']}');
}
}

How can I add request header automatically using http package

Currently I'm sending header with every request like as follow which is very repetitive.
Is there any process so that all my request will have a request header automatically ?
Or how can I avoid code repetition for the following lines:
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String token = sharedPreferences.getString('accessToken');
headers: {
'Contet-type': 'application/json',
'Authorization': 'Bearer $token',
}
My complete API Request code:
Future<http.Response> getAUser(userId) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String token = sharedPreferences.getString('accessToken');
return await http.get(
'$baseUrl/user/$userId/',
headers: {
'Contet-type': 'application/json',
'Authorization': 'Bearer $token',
},
).timeout(Duration(seconds: 30));
}
Yes you can centralize the headers in a separate class!
class BaseService {
Map<String, String> baseHeaders;
Future initBaseService() async {
final preferences = await SharedPreferences.getInstance();
baseHeaders= {
"Accept": "application/json",
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Bearer ${preferences.getString("TOKEN")}",
};
}
}
And then, you can inherit your class with the base class to have access to these methods.
class UserService extends BaseService {
Future<http.Response> getAUser(userId) async {
await initBaseService();
return await http
.get(
'$baseUrl/user/$userId/',
headers: baseHeaders,
)
.timeout(Duration(seconds: 30));
}
}

How to get User's followers using spotify sdk in flutter?

String authToken=await getAuthenticationToken();
final response = await http.get('https://api.spotify.com/v1/me/following', headers: {
'Authorization': 'Bearer $authToken',
});
print('Token: ${authToken}');
print(response.body);
I am getting an error:
Insufficent client scope