Flutter response.body is empty

可紊 提交于 2021-01-07 03:52:24

问题


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 !!


回答1:


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




回答2:


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.




回答3:


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);
  }


来源:https://stackoverflow.com/questions/64942048/flutter-response-body-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!