flutter中http进行网络请求
Posted 伟雪无痕
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flutter中http进行网络请求相关的知识,希望对你有一定的参考价值。
一.flutter 网络请求的三种方式
1.HttpClient请求
实现步骤:
1).导入包
import 'dart:convert';
import 'dart:io';
2).创建HttpClient
var httpClient=HttpClient();
3). Http连接,并获取解析url
var request=await httpClient.getUrl(Uri.parse(url));
这里可以附加参数,并通过HttpClientRequest设置请求header,eg:
Uri uri = Uri(scheme: "https", host: "flutterchina.club", queryParameters:
"name":"jon",
"pwd":"1234"
);
request.headers.add("user-agent", "test");
此处也可设置 Get 请求、Post 请求、Put 请求、Delete 请求,eg :源码
/**
* Opens a HTTP connection using the GET method.
*
* The server is specified using [host] and [port], and the path
* (including a possible query) is specified using
* [path].
*
* See [open] for details.
*/
Future<HttpClientRequest> get(String host, int port, String path);
/**
* Opens a HTTP connection using the GET method.
*
* The URL to use is specified in [url].
*
* See [openUrl] for details.
*/
Future<HttpClientRequest> getUrl(Uri url);
/**
* Opens a HTTP connection using the POST method.
*
* The server is specified using [host] and [port], and the path
* (including a possible query) is specified using
* [path].
*
* See [open] for details.
*/
Future<HttpClientRequest> post(String host, int port, String path);
/**
* Opens a HTTP connection using the POST method.
*
* The URL to use is specified in [url].
*
* See [openUrl] for details.
*/
Future<HttpClientRequest> postUrl(Uri url);
/**
* Opens a HTTP connection using the PUT method.
*
* The server is specified using [host] and [port], and the path
* (including a possible query) is specified using [path].
*
* See [open] for details.
*/
Future<HttpClientRequest> put(String host, int port, String path);
/**
* Opens a HTTP connection using the PUT method.
*
* The URL to use is specified in [url].
*
* See [openUrl] for details.
*/
Future<HttpClientRequest> putUrl(Uri url);
/**
* Opens a HTTP connection using the DELETE method.
*
* The server is specified using [host] and [port], and the path
* (including a possible query) is specified using [path].
*
* See [open] for details.
*/
Future<HttpClientRequest> delete(String host, int port, String path);
/**
* Opens a HTTP connection using the DELETE method.
*
* The URL to use is specified in [url].
*
* See [openUrl] for details.
*/
Future<HttpClientRequest> deleteUrl(Uri url);
4).关闭请求, 等待响应
var response=await request.close();
5).解码响应的内容
if(response.statusCode==HttpStatus.ok)
var json=await response.transform(utf8.decoder).join();
2.http库请求
1). pubspec.yaml 中添加依赖包
dependencies:
flutter:
sdk: flutter
http: '>=0.11.3+12'
2). 代码中导入包
import 'package:http/http.dart' as http;
3).get,post实现
void getRequest() async
var client = http.Client();
http.Response response = await client.get(url);
_ipAddress = response.body;
void postRequest() async
var params = Map<String, String>();
params["name"] = "jon";
params["pwd"] = "1234";
var client = http.Client();
var response = await client.post(uri, body: params);
_ipAddress = response.body;
3.第三方库dio请求
1).参考dio4.0.4
2).参考上一篇:获取flutter中最新的依赖包
二.HttpClient 实现demo展示
class getIpPage extends StatefulWidget
@override
State<StatefulWidget> createState()=> _getIpPageState();
class _getIpPageState extends State<getIpPage>
var _ipAddress="192.168.0.1";
_getIpAddress() async
var url='https://httpbin.org/ip';
var httpClient=HttpClient();
String ipResult;
try
var request=await httpClient.getUrl(Uri.parse(url));
var response=await request.close();
if(response.statusCode==HttpStatus.ok)
var json=await response.transform(utf8.decoder).join();
var data=jsonDecode(json);
ipResult=data['origin'];
else
ipResult =
'Error getting IP address,Http status is: $response.statusCode';
catch(exception)
ipResult = 'Exception,Failed getting IP address';
setState(()
_ipAddress=ipResult;
);
@override
Widget build(BuildContext context)
var stack = Stack(
alignment: Alignment.center,
children: [
Container(
decoration: const BoxDecoration(
color: Colors.black45,
),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Current IP address is: $_ipAddress.',
style: const TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
RaisedButton(
onPressed: _getIpAddress,
child: new Text('Get IP address'),
),
],
)
),
],
);
return stack;
三.效果展示
以上是关于flutter中http进行网络请求的主要内容,如果未能解决你的问题,请参考以下文章