Flutter -------- Http庫實現網絡請求


第三方庫 http實現網絡請求,包含get,post

 

http庫文檔:https://pub.dev/packages/http

 

1.添加依賴

dependencies: http: ^0.12.0 #latest version

 

2.導入庫

import 'package:http/http.dart' as http; //導入前需要配置

 

get

 

var data;

  _fetchGet() async {
    Map newTitle;
    final response =
        await http.get('https://jsonplaceholder.typicode.com/posts/1');
    final responseJson = json.decode(response.body);
    print("請求成功 ---------- "+responseJson.toString());
    newTitle = responseJson;

    setState(() {
      data = newTitle['title'];
      print("title====" + data);
    });
  }

 

post

void _httpPost() async {
    //頭部
    var headers = Map<String, String>();
    headers["loginSource"] = "IOS";
    headers["useVersion"] = "3.1.0";
    headers["isEncoded"] = "1";
    headers["bundleId"] = "com.nongfadai.iospro";
    headers["loginSource"] = "IOS";
    headers["Content-Type"] = "application/json";

    //參數

    Map params = {'v': '1.0','month':'7','day':'25','key':'bd6e35a2691ae5bb8425c8631e475c2a'};

    // 嵌套兩層都可以,但是具體哪個好還有待確認????
    var jsonParams = utf8.encode(json.encode(params));
    // var jsonParams = json.encode(params);

    var httpClient = http.Client();

    var uri = Uri.parse("http://api.juheapi.com/japi/toh");

    http.Response response =
    await httpClient.post(uri, body: jsonParams, headers: headers);

    if (response.statusCode == HttpStatus.ok) {
      print('請求成功');
      print(response.headers);//打印頭部信息
      print("post------${response.body}");
    } else {
      print('請求失敗 code 碼${response.statusCode}');
    }
  }

 


調用:

class HttpMain extends StatefulWidget {
  @override
  createState() => new HttpPage();
}

class HttpPage extends State<HttpMain> {

  @override
  Widget build(BuildContext context) {
    _fetchGet();
    _httpPost();
    return new MaterialApp(
      title: 'Fetch Data Example',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Fetch Data Example'),
        ),
        body: new Center(
          child: new Text("$data"),
        ),
      ),
    );
  }
}

 

控制台

get

 

post

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM