How do i Authorize myself to GET User Api [duplicate] - flutter

The post request is throwing an error while setting the header map.
Here is my code
Future<GenericResponse> makePostCall(
GenericRequest genericRequest) {String URL = "$BASE_URL/api/";
Map data = {
"name": "name",
"email": "email",
"mobile": "mobile",
"transportationRequired": false,
"userId": 5,
};
Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};
return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
print(res);
if (res["code"] != 200) throw new Exception(res["message"][0]);
return GenericResponse.fromJson(res);
});
}
but I'm getting this exception with headers.
══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1 RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)
Anybody facing this issue? I didn't find any clue with the above log.

Try
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': '<Your token>'
};

You can try this:
Map<String, String> get headers => {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer $_token",
};
and then along with your http request for header just pass header as header
example:
Future<AvatarResponse> getAvatar() async {
var url = "$urlPrefix/api/v1/a/me/avatar";
print("fetching $url");
var response = await http.get(url, headers: headers);
if (response.statusCode != 200) {
throw Exception(
"Request to $url failed with status ${response.statusCode}: ${response.body}");
}
var avatar = AvatarResponse()
..mergeFromProto3Json(json.decode(response.body),
ignoreUnknownFields: true);
print(avatar);
return avatar;
}

I have done it this way passing a private key within the headers. This will also answer #Jaward:
class URLS {
static const String BASE_URL = 'https://location.to.your/api';
static const String USERNAME = 'myusername';
static const String PASSWORD = 'mypassword';
}
In the same .dart file:
class ApiService {
Future<UserInfo> getUserInfo() async {
var headers = {
'pk': 'here_a_private_key',
'authorization': 'Basic ' +
base64Encode(utf8.encode('${URLS.USERNAME}:${URLS.PASSWORD}')),
"Accept": "application/json"
};
final response = await http.get('${URLS.BASE_URL}/UserInfo/v1/GetUserInfo',
headers: headers);
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
return new UserInfo.fromJson(jsonResponse);
} else {
throw Exception('Failed to load data!');
}
}
}

Try this
Future<String> createPost(String url, Map newPost) async {
String collection;
try{
Map<String, String> headers = {"Content-type": "application/json"};
Response response =
await post(url, headers: headers, body: json.encode(newPost));
String responsebody = response.body;
final int statusCode = response.statusCode;
if (statusCode == 200 || statusCode == 201) {
final jsonResponse = json.decode(responsebody);
collection = jsonResponse["token"];
}
return collection;
}
catch(e){
print("catch");
}
}

Future<String> loginApi(String url) async {
Map<String, String> header = new Map();
header["content-type"] = "application/x-www-form-urlencoded";
header["token"] = "token from device";
try {
final response = await http.post("$url",body:{
"email":"test#test.com",
"password":"3efeyrett"
},headers: header);
Map<String,dynamic> output = jsonDecode(response.body);
if (output["status"] == 200) {
return "success";
}else{
return "error";
} catch (e) {
print("catch--------$e");
return "error";
}
return "";
}

void getApi() async {
SharedPreferences prefsss = await SharedPreferences.getInstance();
String tokennn = prefsss.get("k_token");
String url = 'http://yourhost.com/services/Default/Places/List';
Map<String, String> mainheader = {
"Content-type": "application/json",
"Cookie": tokennn
};
String requestBody =
'{"Take":100,"IncludeColumns":["Id","Name","Address","PhoneNumber","WebSite","Username","ImagePath","ServiceName","ZoneID","GalleryImages","Distance","ServiceTypeID"],"EqualityFilter":{"ServiceID":${_radioValue2 != null ? _radioValue2 : '""'},"ZoneID":"","Latitude":"${fav_lat != null ? fav_lat : 0.0}","Longitude":"${fav_long != null ? fav_long : 0.0}","SearchDistance":"${distanceZone}"},"ContainsText":"${_txtSearch}"}';
Response response = await post(url , headers: mainheader ,body:requestBody);
String parsedata = response.body;
var data = jsonDecode(parsedata);
var getval = data['Entities'] as List;
setState(() {
list = getval.map<Entities>((json) => Entities.fromJson(json)).toList();
});
}

Related

Retrieving data from http web call in flutter into a list object always empty

List is always empty even though body has contents. I am new to flutter so bare with me if this is basic. I am wanting to get back a list of station data I am coming from a c# background so forgive me if am missing something simple the test string body has the items and can see the items when i debug
class HttpService {
final String url = "url hidden";
final String host = 'url hidden';
final String apiSegment = "api/";
// ignore: non_constant_identifier_names
void login(email, password) async {
try {
Map<String, String> body = {
'username': email,
'password': password,
};
Map<String, String> headers = {'Content-Type': 'application/json'};
final msg = jsonEncode(body);
Response response =
await post(Uri.parse("$url/Login"), headers: headers, body: msg);
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data['jwtToken']);
print('Login successfully');
final prefs = await SharedPreferences.getInstance();
await prefs.setString('jwtToken', data['jwtToken']);
List<Stations> stationData = await getStationData('11');
var test = stationData;
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
List<Stations> stationData = <Stations>[];
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var body2 = body.toString();
stationData = body
.map(
(dynamic item) => Stations.fromJson(item),
)
.toList();
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
print(e.toString());
}
return stationData;
}
}
I am calling my function from the same class
List<Stations> stationData = await getStationData('11');
Data from body
Actually the problem is you are returning the data after the end of try catch.
Try this
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
final stationData = List<Stations>.from(body.map((item) => Stations.fromJson(item))); // made some changes
return stationData;
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
rethrow;
}
}
I hope this will help you

Flutter upload image

Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown
Future<dynamic> getPhotoUrl(int profileID) async {
print("get Photo url $profileID");
var client = http.Client();
var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
Map<String, String> headers = {
'APIVersion': '1',
"Authorization": token,
};
var response = await client.get(url, headers: headers);
if (200 == response.statusCode) {
return response.body;
} else {
}
print("avatar url: $currentPhotoUrl");
}
tried this and it doesn't work
Future<void> getPhotoUrl(int profileID) async {
print("get photo url $profileID");
var client = http.Client();
Map<String, String> headers = {
"Authorization": token
};
final http.Response response = await client.get(
Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
headers: headers);
if (response.statusCode == 200) {
Map responseBody = jsonDecode(response.body);
var data = responseBody["data"];
if (data.length < 1) {}
else {
currentPhotoUrl.value = data[0]["content"][0]["medium"];
}
} else {
throw WebSocketException("server error: ${response.statusCode}");
}
print("photos url: $currentPhotoUrl");
}

how to post form data request using flutter in http package

I want to send form data in flutter using the HTTP package. Getting the error:FormatException: Unexpected character (at character 1)
I/flutter (30465):
I am sending the form data in the HTTP post request.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = 'https://yobimx.com/citykey/api/users/login';
final response = await http.post(url, body: {
'email': 'usamashafiq199#outlook.com',
'password': '123',
}, headers: {
"Content-Type": "application/x-www-form-urlencoded",
});
print(
json.decode(response.body),
);
final responseData = json.decode(response.body);
} catch (error) {
print(error);
}
}
I have to use a multipart request for request. Thanks for your help.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = Uri.parse('https://yobimx.com/citykey/api/users/login');
Map<String, String> requestBody = <String, String>{
'email': 'usamashafiq199#outlook.com',
'password': '123'
};
var request = http.MultipartRequest('POST', url)
..fields.addAll(requestBody);
var response = await request.send();
final respStr = await response.stream.bytesToString();
print(
jsonDecode(respStr),
);
print("This is the Status Code$respStr");
var encoded = json.decode(respStr);
print(encoded['status']);
print('This is the userId${encoded['data']['user_id']}');
} catch (error) {
print(error);
}
}

How to format body for form-data header

This might be probably already answered question but I can not find one. How do we format data body for form-data http response? I tried to encode it to json but that didn't work with error
Unhandled Exception: Multipart: Boundary not found
Future<void> createProfile() async {
final body = {
"firstName": "first",
"lastName": "last",
"image": "path-to-image"
};
try {
final http.Response response = await http.post(APIPath.createProfile(),
headers: {"Authorization": "Bearer $token","Content-Type": "multipart/form-data"},
body: json.encode(body)); //<-- this doesn't work
final jsonResponse = json.decode(response.body);
if (response.statusCode != 201) {
throw HttpException(jsonResponse["error"]);
}
} catch (error) {
throw error;
}
}
Flutter Documentation
var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri)
..headers['authorization'] = 'auth header value'
..fields['user'] = 'nweiz#google.com'
..files.add(await http.MultipartFile.fromPath(
'package', 'build/image.png',
contentType: MediaType('image', '*')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

How to set headers for POST with flutter and Dio

this is my code below, i'm stuck please help.
void getProducts() async {
String htoken = Utils.prefs.getString("token");
print(htoken);
try {
var dio = Dio(BaseOptions(headers: {"appusertoken": "$htoken"}));
//dio.options.headers["appusertoken"] = "$htoken";
Response response = await dio.post(
'APIURL',
);
print("data coming");
print(response.data);
} on DioError catch (e) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
}
}
it was throwing an error of data null.
I was able to fix the issues.
Add optional parameter options for dio.post method and define headers with Options class:
void getProducts() async {
String htoken = Utils.prefs.getString("token");
try {
Dio dio = Dio();
Response response = await dio.post("http://URL",
data: {},
options: Options(
headers: {"appusertoken": "$htoken"},
));
print("data coming");
print(response);
} on DioError catch (e) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
}
}
For example :
Dio _dio = new Dio();
_dio.options.contentType = Headers.formUrlEncodedContentType;
_dio.options.headers['Authorization'] = 'bearer $authToken';
or use :
final Map<String, dynamic> header = {'Authorization': 'bearer $authToken'};
enter code here
final responseData = await _dio.get(
Apis.account_profit,
options: RequestOptions(
method: 'GET', headers: header, baseUrl: Apis.apiBaseUrl),
);