Flutter: I try to get api from backend with authorization bearer token in header using dio pack and http , i got Exception but is working in postman - flutter

This is my code
Future<List<ContentHome>>getContentHome()async{
final response = await http.get(
Uri.parse('http://IPServerBackend/api/content/getAllContentHome/2?pgsize=10&pgnum=1'),
// Send authorization headers to the backend.
headers: {
"Accept": 'application/json',,
"Content-Type" : "application/json",
"Authorization": "Bearer MyToken",
},
);
final responseJson = jsonDecode(response.body);
return (responseJson as List).map(
(e) => ContentHome.fromJson(e),
).toList();
}
The Exception:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected
How to solve this?

Related

One or more validation errors occurred in a get request with Basic Authentication authorization

I am working with basic authentication in a get request, and it takes parameters, but it throws the following error as a status code and response body.
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-5bebf6cfcb0e1cec5306c5dbff1cf6c0-c432aba0a422c830-00","errors":{"password":["The password field is required."],"user_name":["The user_name field is required."]}}.
I don't know what it means and what should I fix in my code. Can anybody help me, here is my code:
String basicAuth =
'Basic ${base64.encode(utf8.encode('$_email:$encodedPassword'))}';
var queryParams = {
'domain_name': 'domainName',
'token': 12345.toString(),
};
final uri =
Uri.https(baseUrl, '/api/Employee/validate_user', queryParams);
final res = await http.get(uri, headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.authorizationHeader: basicAuth,
});
if (res.statusCode == 200) {
debugPrint(res.body);
}else {
debugPrint("Status " + res.statusCode.toString());
debugPrint(res.body);
}

Flutter http can't get Bearer Token from .NET Api

I am starting flutter mobile development and have problem with http package http calls. I already have working API written in .NET with included Micorosft Identity. My goal is to create flutter mobile app that gets data from that API with authorizauion. I have problems implementing username-password authorization to get Token from API. Same API call works on Postman and in my existing Xamarin Forms App. Same problem with http call where in its header I use token which I get from Postman. Using VS Code, all packages installed, can retrive sample data from openweathermap.org in same flutter app. My code is:
Recive Bearer Token from API:
Future<String> authorization(String username, String password) async {
Uri uri = Uri.parse('https://myapi/token');
var request = http.MultipartRequest('POST', uri);
request.fields.addAll({
'grant_type': 'password',
'username': username,
'password': password,
});
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
Map<String, dynamic> auth =
jsonDecode(await response.stream.bytesToString());
return auth['access_token'];
} else {
return "";
}
}
GET Cars Data from API:
Future<String> getCars() async {
Uri uri = Uri.parse('https://myapi/api/getcars');
var token =
'WorkingToken';
http.Response response = await http.get(uri, headers: {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "Bearer $token",
});
return response.body;
}
Microsoft Identity Authorization request expects application/x-www-form-urlencoded content.
Future<String> authorization(String username, String password) async {
final response = await http.post(
Uri.parse('https:/host/path/token'),
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
},
body: <String, String>{
'grant_type': 'password',
'username': username,
'password': password,
},
encoding: Encoding.getByName('utf-8')
);
if (response.statusCode == 200) {
return jsonDecode(response.body)['access_token'];
} else {
throw Exception(response.reasonPhrase);
}
}
Your question is very general and your problem depends on your response data. Of course, I did not realize that you have a problem receiving the token or using the token as a header for another api!
But since you are just starting to use Flutter, I suggest you to use the Chopper Library to work with HTTP services and api.
It's very simple and fase.

Facing some issues in Flutter REST API using with JWT token

I'm facing some issues in Flutter REST API using with JWT token
Here the header authentication was not passing properly. But it working good in Postman
**Example Code:**
String url = "project URL";
String token = "generated jwt token";
var headers = {
'Authorization': token,
'Cookie': 'ci_session=u17u9effeqk5fdhl1eqdh4jsmu3o3v29'
};
var request = http.Request('GET', Uri.parse(url));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
If I try without the JWT token by removing it in the backend it's working properly. But I need to work with JWT.
Can anyone please help to fix this issue?
I use dio package to work with the same...
// Import dio package
Future<void> function() async {
Dio dio = new Dio();
String url = 'example.com';
try {
final response = await dio.post(
url,
options: Options(
headers: {'Authorization': 'Bearer $userToken'}, //This is where you define your header and provide jwt token
),
);
} on DioError catch (error) {
if (error.response!.statusCode == 401) {
print(error.response.toString());
throw Error();
}
print(error);
throw Error();
}
}
}
The package can be found here https://pub.dev/packages/dio
Feel free to clear up any confusions
The most likely issue here is the value that you give in your header.
For Bearer tokens, the value given in the Authorization header must be Bearer followed by the value of your token. If you did not implement some specific/homemade authorisation function in your backend, this must be what is expected to be received.
Try replacing 'Authorization': token, by
'Authorization': `Bearer $token`,
and it shouldd work as intended.

HTTP GET : Header (Authorization : Bearer Token)

I am making a request in postman with the same URL mentioned below in the code and in the header passing accept and Authorization with bearer token.
In postman it is working completely fine and giving desired response but in flutter in my code it is giving 403-Forbidden Request its somehow not passing the token(i am assuming).
Future<ApiResponse<String>> getCompanyList() {
String token =
" ";
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: "application/json",
HttpHeaders.authorizationHeader: "Bearer $token",
};
final String API = "https://.............";
return http.get(API,headers: headers).then((data) {
if (data.statusCode == 200 ) {
final jsonData = json.decode(data.body);
return ApiResponse<String>(data: jsonData, error: false, errorMessage: "");
}
return ApiResponse<String>(error: true, errorMessage: data.statusCode.toString());
}).catchError((_) => ApiResponse<String>(error: true, errorMessage: "An Error Occureddddd!!!"));
}
}
This is my Service Class i am calling it from my Dart class anf it is calling fine.
class ApiResponse<T> {
T data;
bool error;
String errorMessage;
ApiResponse({this.data, this.error = false, this.errorMessage});
}
ApiResponse.dart
you should pass the headers as a map
something like this
var res = await http.post(url, body: body,headers: {
"Accept": "*/*",
"Content-Type" : "application/json",
"Authorization" : "Bearer $token"
},);

How can pass the request parameter as a formdata in dart or flutter

I have tried many formats to pass the request parameter in the flutter project but I'm getting API status code 415 and Unhandled Exception: FormatException: Unexpected end of input (at character 1).
I have added the postman image for the understanding of the form data.
For Flutter HTTP library it goes like this,
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var request = http.Request('POST', Uri.parse(''));
request.bodyFields = {
'firstName': 'Keval',
'lastName': 'ebiz',
'email': 'al#gmail.com',
'phone': '1234'
};
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}