Sunday, 11 October 2020

通过HttpClient发起HTTP请求

 

Dart IO库中提供了用于发起Http请求的一些类,我们可以直接使用HttpClient来发起请求。使用HttpClient发起请求分为五步:

1 创建一个HttpClient

HttpClient httpClient = new HttpClient();
2 打开Http连接,设置请求头:
HttpClientRequest request = await httpClient.getUrl(uri);

这一步可以使用任意Http Method,如httpClient.post(...)httpClient.delete(...)等。如果包含Query参数,可以在构建uri时添加,如:

Uri uri=Uri(scheme: "https", host: "flutterchina.club", queryParameters: { "xx":"xx", "yy":"dd" });

通过HttpClientRequest可以设置请求header,如:

request.headers.add("user-agent", "test");

如果是post或put等可以携带请求体方法,可以通过HttpClientRequest对象发送request body,如:

String payload="..."; request.add(utf8.encode(payload)); //request.addStream(_inputStream); //可以直接添加输入流 

3 等待连接服务器:

HttpClientResponse response = await request.close();

这一步完成后,请求信息就已经发送给服务器了,返回一个HttpClientResponse对象,它包含响应头(header)和响应流(响应体的Stream),接下来就可以通过读取响应流来获取响应内容。

4 读取响应内容:

String responseBody = await response.transform(utf8.decoder).join();

我们通过读取响应流来获取服务器返回的数据,在读取时我们可以设置编码格式,这里是utf8。

5 请求结束,关闭HttpClient

httpClient.close();

关闭client后,通过该client发起的所有请求都会中止。

示例

我们实现一个获取百度首页html的例子


 

https://book.flutterchina.club/chapter11/http.html

 

 

 

 

 

 
 

No comments:

Post a Comment

zomok E-commerce system plan. Choose your online ordering system. No-risk 30 day free trial. Then USD 9/month. No credit card required.

zomok E-commerce system plan. Choose your online ordering system. No-risk 30 day free trial. Then USD 9/month. No credit card required. h...