1

HTTP package用于发出 API 请求,但是当我发出请求时,它返回给我Html response.

import 'package:clima/services/location.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();
    getLocation();
  }

  void getLocation() async {
    Location location = new Location();
    await location.getCurrentLocation();

    print(location.latitude);
    print(location.longitude);
  }

  void getData() async {
    final url =
        'samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22';
    http.Response response = await http.get(Uri.parse(url));
    print(response.body);
  }

  @override
  Widget build(BuildContext context) {
    getData();
    return Scaffold();
  }
}

在这里,当我打印response body它时,它会返回给我 HTML 源代码而不是“JSON”

这就是我得到的回应......

响应文本的图像

我需要帮助才能从 API 获取有效的 JSON 响应,而不是 HTML 响应。

编辑:现在解决了!

4

1 回答 1

2

您的网址不完整。

更改此代码

void getData() async {
    final url =
        'samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22';
    http.Response response = await http.get(Uri.parse(url));
    print(response.body);
  }

对此,

void getData() async {
    final url =
        'https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22';
    http.Response response = await http.get(url));
    print(response.body);
  }

让我们知道它是否有效。

于 2021-05-14T05:25:13.697 回答