flutterdarthttphttp-status-code-401dio

401 unAuthorized response when making get request in flutter with Dio or http packages


I am facing a big problem when I am making an http get request to a server when using both dio and http packages, I am sending a token in the header of request, but always get 401 unauthorized response, despite this request and token work fine in postman but when I am making the request using flutter always gets 401 unauthorized, so if any when could help me

I tried to make the get request using dio and http but get the same 401 response. Checked the token in postman and it works fine,
checked http io in external packages to prevent the package to convert header to small case.
Assured the backend receives small case letters in headers, but always get same 401 errors.

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:graduation_project/core/localStorage/shared_preferences_storage.dart';
import '../../../core/constants/shared_pref_constants.dart';

class ItemsCartCall {
  static Future<List<dynamic>> getCartItems() async {
    final bearerToken =
        SharedPreferencesManager.getString(LocalStorageConstants.userToken);
    if (bearerToken == null || bearerToken.isEmpty) {
      throw Exception('Bearer token is missing or invalid');
    }
    final headers = {
      'Authorization': 'Bearer $bearerToken',
      'Accept': 'application/json',
    };

    final response = await http.get(
      Uri.parse('http://ikseer.onrender.com/orders/cart/'),
      headers: headers,
    );
    (response.body.toString());
    if (response.statusCode == 200) {
      final res = jsonDecode(response.body);

      await SharedPreferencesManager.storeStringVal(
          LocalStorageConstants.cartId, res['id']);

      return List<dynamic>.from(res['items']);
    } else if (response.statusCode == 401) {
      debugPrint(response.headers.toString());
      debugPrint(response.body.toString());

      throw Exception(response.body);
    } else {
      debugPrint(response.body.toString());
      throw Exception(
          'Server responded with status code: ${response.statusCode}');
    }
  }
}


Solution

  • Make sure that your request was sent with HTTPS protocol