Guest
Guest

Reputation: 127

How to make https calls in Flutter?

I am new to flutter development. I am trying hard to make the https calls work. Whenever I call a https URL, it throws the below error:

SocketException: Failed host lookup: 'someserver.com' (OS Error: nodename nor servname provided, or not known, errno = 8)

Below is the code I am using:

final ioc = new HttpClient();
    ioc.badCertificateCallback =
        (X509Certificate cert, String host, int port) => true;
    final http = new IOClient(ioc);
    return http
        .post(url, body: body, headers: headers, encoding: encoding)
        .then((response) {
      final String res = response.body;
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while posting data");
      }
      return _decoder.convert(res);
    });

I have checked below few links and many more and tried all of them but nothing seems to work.

Also please note that I am able to access the server from the browser. Same server is being access from iOS app as well(built using XCode). From iOS I am able to access the server.

Kindly help!

Upvotes: 0

Views: 1578

Answers (2)

Khawar Hussain
Khawar Hussain

Reputation: 1

Import these two packages on the top

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

and then here is the sample code

    void main(List<String> arguments) async {
      
     var response= await get(Uri.parse("your URL with http:// or https://"));

      if (response.statusCode == 200) {

        var jsonResponse =
            convert.jsonDecode(response.body) as Map<String, dynamic>;
        var itemCount = jsonResponse['totalItems'];
        print('Count: $itemCount.');
      
} else {
        print('Request failed with status: ${response.statusCode}.');
      }
    }

Upvotes: 0

Gourango Sutradhar
Gourango Sutradhar

Reputation: 1619

The http package provides the simplest way to fetch data from the internet.

To install the http package, add it to the dependencies section of the pubspec.yaml file. You can find the latest version of the http package to here

dependencies:
  http: <latest_version>

Import the http package.

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

Additionally, in your AndroidManifest.xml file, add the Internet permission.

<uses-permission android:name="android.permission.INTERNET" />

Then like the below function, you will be able to get/fetch/post HTTP call

Future<http.Response> getchData() {
  return http.get('https://jsonplaceholder.typicode.com/albums/1');
}

For Advanced HTTP call and management you can use Dio plugin

Upvotes: 1

Related Questions