Alvin John Babu
Alvin John Babu

Reputation: 2070

Flutter: How to add headers to http package in flutter

I am trying to call the below API using the flutter package http, The structure of the request is

GET /api/v3/4870020/products/123123?lang=en&token=123456789abcd HTTP/1.1
Host: app.ecwid.com
Content-Type: application/json;charset=utf-8
Cache-Control: no-cache

How can I call this API using http package.

Upvotes: 0

Views: 1741

Answers (2)

Firat
Firat

Reputation: 356

You can use get() from http package. Try this:

  Future<void> fetchData(String lang, String token) async {
    final host = "app.ecwid.com"; // this is your baseUrl
    final apiPath = "api/v3/4870020/products/123123"; // which api do you want to use?
    final url = "https://$host/$apiPath?lang=$lang&token=$token"; // final url
    final response = await http.get(
      url,
      headers: {
        "Content-Type": "application/json",
        "Cache-Control": "no-cache"
      }
    );

    if(response.statusCode == 200) {
      // do some stuff with the received data.
    }
    else return;
  }

As you can see, we are specifying the language and token parameters to the end of the url.

See the documentation

Upvotes: 2

mcfly
mcfly

Reputation: 834

you have to create your own client and override send method to add your headers

class HttpClient extends http.BaseClient {
    final http.Client _client = http.Client(); //your http client

    @override
    Future<http.StreamedResponse> send(http.BaseRequest request) {
        //add your headers in request here
        return this._client.send(request)
    }

}

Upvotes: 2

Related Questions