3

I am having a weird error in flutter where just adding an authorization header allows me to have an error.

Current Problem I am having,

  postData(data, apiUrl) async {
    var fullUrl = _url + apiUrl;

    var at = await _accessToken;
    print('access token is $at');

    return await http.post(
      Uri.parse(fullUrl),
      body: jsonEncode(data),
      encoding: Encoding.getByName("utf-8"),
      headers: {
        'Authorization': 'Bearer $at',    <---------------- Adding this line of code prints an error in the console
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
    );

In my code, if I add the Authorization header that I am pointing to with an arrow in the above code I receive an error on the console that says,

D/libc-netbsd(32217): [getaddrinfo]: mtk hostname=host_name_i_provided; servname=(null); cache_mode=(null), netid=0; mark=0; app_uid=10217; ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0 D/libc-netbsd(32217): getaddrinfo: host_name_i_provided get result from proxy >> E/flutter (32217): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Unexpected character (at line 3, character 1) E/flutter (32217): E/flutter (32217): ^ E/flutter (32217): E/flutter (32217): #0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1404:5) E/flutter (32217): #1
_ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1271:9) E/flutter (32217): #2
_ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:936:22) E/flutter (32217): #3
_parseJson (dart:convert-patch/convert_patch.dart:40:10) E/flutter (32217): #4 JsonDecoder.convert (dart:convert/json.dart:506:36) E/flutter (32217): #5 JsonCodec.decode (dart:convert/json.dart:157:41) E/flutter (32217): #6
_RescueMeFormPageState.submitData (package:redcross/Pages/Disaster/rescue_me_form_page.dart:57:21) E/flutter (32217): E/flutter (32217):

But if I remove that header, I get the following valid response,

I/flutter (32217): {status: 400, data: {code: TokenException, message: Authorization Token not found}}

I can not figure out why I am getting this error.

A few more things I would like to point out is, the $at variable holds the correct access token. I verified this by adding print statements. So the line of code 'Authorization': 'Bearer $at', is valid.

Also If I do the same request from the postman I get a valid response.

Can someone please help me figure out a solution to this error. Thanks.....

nvoigt
  • 75,013
  • 26
  • 93
  • 142

1 Answers1

0

The problem is not with token it is with JSON parsing check the code at which you are parsing the response.

Nikhil Biju
  • 645
  • 7
  • 8