Oussama Belabbas
Oussama Belabbas

Reputation: 196

Flutter response.body is empty

I am working with this API where I make an http request to this site to retrieve my Data

https://fantasy.premierleague.com/api/bootstrap-static/

first time when I used it I couldn't retrieve any data, after some researches I solved the problem with a simple flutter upgrade ( I couldn't know what was the problem or why it was solved after the upgrade ), then after somedays I was working on the project and the problem occurred again and I am getting an empty body every Time I try to make a request

http.get("https://fantasy.premierleague.com/api/bootstrap-static/")

I'm using this line to get a Response value and then try to decode it to JSON value but this error happens

exeption occured : FormatException: Unexpected end of input (at character 1)

I already know that this error happens because I am trying to decode an empty body, but I can't understand why this is happening

Note: I tried multiple other APIs urls and they all work properly !!

Upvotes: 0

Views: 3433

Answers (3)

Oussama Belabbas
Oussama Belabbas

Reputation: 196

So I end up switching to flutter master and the code worked perfectly, I still don't know why it doesn't work on stable but works on master. anyway if anyone is having this issue just switch to master and it should work fine. Thanks.

Upvotes: 1

Mr Random
Mr Random

Reputation: 2218

you should add await keyword before http.get() because it is an asynchronous function

await http.get("https://fantasy.premierleague.com/api/bootstrap-static/")

EDIT: The following code is tested and working

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

  fetchData() async {
    var res = await http
        .get("https://fantasy.premierleague.com/api/bootstrap-static/");
    var jsonData = jsonDecode(res.body);
    print(jsonData);
  }

Upvotes: 0

Akshar Patel
Akshar Patel

Reputation: 9378

If you dump headers using cURL, this is what I got:

HTTP/1.1 301 Moved Permanently
Server: Varnish
Retry-After: 0
Location: https://fantasy.premierleague.com/api/bootstrap-static/
Content-Length: 0
Accept-Ranges: bytes
Date: Sat, 21 Nov 2020 15:58:17 GMT
Via: 1.1 varnish
Connection: close
X-Served-By: cache-bom4748-BOM
X-Cache: HIT
X-Cache-Hits: 0
X-Timer: S1605974297.185069,VS0,VE0

HTTP/2 200 
server: Varnish
retry-after: 0
content-type: application/json
accept-ranges: bytes
date: Sat, 21 Nov 2020 15:58:17 GMT
via: 1.1 varnish
x-served-by: cache-bom4732-BOM
x-cache: MISS
x-cache-hits: 0
x-timer: S1605974297.371758,VS0,VE0
content-length: 0

the Request is getting redirected but in dart/flutter there seems to be no way to solve this as of now.

Check these answers:

https://stackoverflow.com/a/54832309/6156989

https://stackoverflow.com/a/56862713/6156989

Upvotes: 2

Related Questions