0

I want to make a simple post request, but something isn't working.

In front-end angular the http headers are made like this:

let header = {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        user: JSON.stringify(JSON.parse(localStorage.getItem("user")).values)
      })
    };

at app Flutter i was trying to do something like that, but everything I'm doing returns error 500 because the headers isn't right

technically i would need to do like that

final Map< String, String> headers = {
      "Content-Type" : "application/json",
      "user" : { 
                 "token": "BLABLABLA",
                 "user_id" : "1"
               } 
} ;

This would have to work just like the front end of the angular because the back end was done like this

the login is done and working, we are saving the login information with SharedPreferences

1 Answer 1

2

This is a good question. Lots of people out there use wrapper libraries for the base http library, but it sounds like you are using just the base library. I think the problem is that you are building a header as if it were Map<String, dynamic> when it actually needs to be Map<String, String>.

Depending on your server setup, you could probably get this to work like so:

final Map< String, String> headers = {
  "Content-Type" : "application/json",
  "user" : jsonEncode({ // add this function call around your object
             "token": "BLABLABLA",
             "user_id" : "1"
           }),
};

Using this above will create two headers:

Content-Type: application/json
user: {"token":"BLABLABLA","user_id":1}

However you may not want that, because some servers do not like the {} or "" characters in the content of the header. Instead you can do two more variations:

= Base 64 method =

try to base64 that json string in your header, then on the server side base64decode it:

final Map< String, String> headers = {
  "Content-Type" : "application/json",
  "user" : stringToBase64.encode( // additionally base64 encode it
             jsonEncode({ // add this function call around your object
               "token": "BLABLABLA",
               "user_id" : "1"
             }),
           ),
};

= URL Encode method =

urlencode that header which should work for most servers:

final Map< String, String> headers = {
  "Content-Type" : "application/json",
  "user" : Uri.encodeQueryComponent( // additionally base64 encode it
             jsonEncode({ // add this function call around your object
               "token": "BLABLABLA",
               "user_id" : "1"
             }),
           ),
};

= Suggestion =

If you are just trying to use a basic JWT though, you may want to just skip that whole user parameter and stick your token into a standard Authorization: Bearer TOKEN format. Here is a working sample that I have pulled and modified from one of my projects that does exactly that:

import 'dart:convert';
import 'package:http/http.dart' as http;

String _getToken() {
  return 'MY_BEARER_TOKEN';
}

class BaseNetworking {
  Future<http.Response> post(
    String url,
    Map<String, dynamic> data, {
    Map<String, String> headers,
  }) async {
    final Uri uri = Uri.parse(url);

    return await http.post(
      uri,
      headers: _buildHeaders(
        requiresAuth: true,
        extra: headers,
      ),
      body: jsonEncode(data),
    );
  }

  /// build the headers for the given request. might include authorization or any number of other headers
  Map<String, String> _buildHeaders({
    bool requiresAuth = true,
    Map<String, String> extra,
  }) {
    final Map<String, String> headers = <String, String>{
      'Accept': 'application/json; charset=utf-8',
      'User-Agent': 'AppName (version: 1.0.0)',
    };

    if (extra is Map<String, String>) {
      headers.addAll(extra);
    }

    if (requiresAuth) {
      headers['Authorization'] = 'Bearer ${_getToken()}';
    }

    return headers;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, incredible answer, it worked here! after my demand I will try to change to the proposed suggestion
glad to help @vitor-ezequiel

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.