1

I am using HTTP package for making API requests but when I make a request it returns me with 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();
  }
}

here when I print response body it returns me with HTML source code instead of 'JSON'

this is what I get as a response...

an image of the response text

I need help with getting a valid JSON response from the API and not an HTML response.

EDIT: it is now solved!

vandit vasa
  • 413
  • 4
  • 20

1 Answers1

2

Your URL is not complete.

Change this code

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

to this,

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

Let us know if it worked.

Ratnadeep
  • 1,125
  • 1
  • 15
  • 30
  • what error? edit and add in your question... otherwise try http instead of https – Ratnadeep May 14 '21 at 05:30
  • check I have edited the code. inside http.get() only use url, do not need Uri.parse() ... just use http.get(url) .. let me know if it works – Ratnadeep May 14 '21 at 05:36
  • The argument type 'String' can't be assigned to the parameter type 'Uri' => this error is being thrown – vandit vasa May 14 '21 at 05:37
  • please check the updated code in my answer. I removed that http.get(Uri.parse()) ... use only http.get(url). ... it works perfectly fine for me. – Ratnadeep May 14 '21 at 05:39
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232379/discussion-between-ratnadeep-chakraborty-and-vandit-vasa). – Ratnadeep May 14 '21 at 05:44
  • Have similar problem with this question, thank you for your help good sir. – Prisma Putra Apr 30 '22 at 09:09