Home > Back-end >  Flutter http post request gives status code 401
Flutter http post request gives status code 401

Time:08-18

I am using API to verify phone number provided by user.... on postman api give perfect response and give OTP code in response but in flutter status code 401 is returned here is my code

 Future verifyPhone(String phoneNumber) async {
    try {
      String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
      var body = <String, String>{};
      body['user_number'] = phoneNumber;
      var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
      var response = await http.post(
        url,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "authentication": "Bearer $token"
        },
        body: body,
      );
      if (response.statusCode == 200) {
        print("Code sent");
      } else {
        print("Failed to send code");
        print(response.statusCode);
      }
    } catch (err) {
      print(err.toString());
    }
notifyListeners();
  }

instead of "code sent" i get "failed to send code" and status code 401

CodePudding user response:

EDIT You can send form request this way

  Future verifyPhone(String phoneNumber) async {
    try {
      String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
      var body = <String, String>{};
      body['user_number'] = phoneNumber;
      var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
      
      var headers  ={
        
         "Content-Type": "application/x-www-form-urlencoded",
          "authentication": "Bearer $token"
      };
      
  var request = http.MultipartRequest('POST', url)
    ..headers.addAll(headers) 
    ..fields.addAll(body);
    
      http.StreamedResponse response = await request.send();
  
      if (response.statusCode == 200) {
        print("Code sent");
      } else {
        print("Failed to send code");
        print(response.statusCode);
      }
    } catch (err) {
      print(err.toString());
    }
notifyListeners();
  }

EDIT

To access :

var  _data = jsonDecode(response);
  
  var list = _data["data"];
  
  print(list[0]['otp_code']); 
  • Related