tharakadil95
tharakadil95

Reputation: 13

How to pass Authorization header in API POST call in dart?

I'm working with flutter application and I want to know how we pass an authorization header in POST request. Here is the code I tried. I need help to know how to do this in the correct way.

    Future<String> addCartItemToDb({String userId}) async {
    try {
      final res = await http.post(
        _baseURL,
        headers: {
          "Content-Type": "application/json",
          "accept": "*/*",
          "Authorization": "token"
        },
        body: jsonEncode({"userId": userID})
      );
      return _response(res);
    }on SocketException {
      throw CustomException("No internet Connection");
    }on FormatException {
      throw CustomException("Bad Response format !");
    }
  }

Further, I want to know how we decode that token I passed in the header to get userid to that user who already logged in.

Upvotes: 0

Views: 3197

Answers (2)

Simant Dhakal
Simant Dhakal

Reputation: 61

final uri = Strings.base_url_api+Strings.nearby_cons;

var requestBody = {
  "organization_id": _orgID.toString()
};

http.Response response = await http.post(uri,
  headers: <String, String>{
    'Content-Type': 'application/json',
    'Authorization': 'Bearer $_auth'
  },
  body: requestBody,
);

if (response.statusCode == 200) {

  var responseJson = json.decode(response.body);
  print(responseJson);

} else {
  print('Status code error.. Check your API method or URL.. ');
}

Upvotes: 2

Atul Dwivedi
Atul Dwivedi

Reputation: 34

final jobsListAPIUrl = constants.BASE_URL+'bookings/retail/0/20/?status='+constants.BOOKING_CONFIRM_KEY+'&filter=0'; print(jobsListAPIUrl); var response = await http.get(jobsListAPIUrl,headers: {'Authorization':'Token '+widget.token}); print(response.body);

Upvotes: -1

Related Questions