Flutter http headers
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!'); } }}