首先你需要導(dǎo)入:
dio: ^2.1.3
cookie_jar: ^1.0.0
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:cookie_jar/cookie_jar.dart';
class HttpGo {
static final StringGET ="get";
? static final StringPOST ="post";
? static final StringDATA ="data";
? static final StringCODE ="errorCode";
? Diodio;
? static HttpGo_instance;
? BaseOptionsoptions;
? static HttpGogetInstance() {
if (_instance ==null) {
_instance =HttpGo();
? ? }
return _instance;
? }
HttpGo() {
//BaseOptions疗绣、Options线召、RequestOptions 都可以配置參數(shù),優(yōu)先級(jí)別依次遞增多矮,且可以根據(jù)優(yōu)先級(jí)別覆蓋參數(shù)
? ? options =new BaseOptions(
//請(qǐng)求基地址,可以包含子路徑
? ? ? baseUrl:"http://192.168.5.6:8085",
? ? ? //Http請(qǐng)求頭
? ? ? headers: {'platform':'android', 'version':11.0},
? ? ? //連接服務(wù)器超時(shí)時(shí)間缓淹,單位是毫秒.
? ? ? connectTimeout:5000,
? ? ? //響應(yīng)流上前后兩次接受到數(shù)據(jù)的間隔,單位為毫秒塔逃。
? ? ? receiveTimeout:100000,
? ? ? //請(qǐng)求的Content-Type讯壶,默認(rèn)值是[ContentType.json]. 也可以用ContentType.parse("application/x-www-form-urlencoded")
? ? ? contentType: ContentType.json,
? ? ? //表示期望以那種格式(方式)接受響應(yīng)數(shù)據(jù)。接受三種類型 `json`, `stream`, `plain`, `bytes`. 默認(rèn)值是`json`,
? ? ? responseType: ResponseType.plain,
? ? );
? ? dio =Dio(options);
? ? //cookie管理
? ? dio.interceptors.add(CookieManager(CookieJar()));
? ? //添加攔截器
? ? dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options){
print("請(qǐng)求之前");
? ? ? return options;
? ? },onResponse: (Response response){
print("響應(yīng)之前");
? ? ? return response;
? ? },onError: (DioError e){
print("錯(cuò)誤之前");
? ? ? return e;
? ? }));
? }
/*
? * get請(qǐng)求*/
? get(url, {data, options, cancelToken})async {
Response response;
? ? try {
response =await dio.get(url, queryParameters: data, options: options, cancelToken: cancelToken);
? ? ? print('get success---------${response.statusCode}');
? ? ? print('get success---------${response.data}');
//? ? ? response.data; 響應(yīng)體
//? ? ? response.headers; 響應(yīng)頭
//? ? ? response.request; 請(qǐng)求體
//? ? ? response.statusCode; 狀態(tài)碼
? ? }on DioErrorcatch (e) {
print('get error---------$e');
? ? ? formatError(e);
? ? }
return response.data;
? }
/*
? * post請(qǐng)求*/
? post(url, {data, options, cancelToken})async {
Response response;
? ? try {
response =await dio.post(url, queryParameters: data, options: options, cancelToken: cancelToken);
? ? ? print('post success---------${response.data}');
? ? }on DioErrorcatch (e) {
print('post error---------$e');
? ? ? formatError(e);
? ? }
return response.data;
? }
/*
? * 下載文件*/
? downloadFile(urlPath, savePath)async {
Response response;
? ? try {
response =await dio.download(urlPath, savePath,onReceiveProgress: (int count, int total){
//進(jìn)度
? ? ? ? print("$count $total");
? ? ? });
? ? ? print('downloadFile success---------${response.data}');
? ? }on DioErrorcatch (e) {
print('downloadFile error---------$e');
? ? ? formatError(e);
? ? }
return response.data;
? }
/*
? * error統(tǒng)一處理*/
? void formatError(DioError e) {
if (e.type == DioErrorType.CONNECT_TIMEOUT) {
// It occurs when url is opened timeout.
? ? ? print("連接超時(shí)");
? ? }else if (e.type == DioErrorType.SEND_TIMEOUT) {
// It occurs when url is sent timeout.
? ? ? print("請(qǐng)求超時(shí)");
? ? }else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
//It occurs when receiving timeout
? ? ? print("響應(yīng)超時(shí)");
? ? }else if (e.type == DioErrorType.RESPONSE) {
// When the server response, but with a incorrect status, such as 404, 503...
? ? ? print("出現(xiàn)異常");
? ? }else if (e.type == DioErrorType.CANCEL) {
// When the request is cancelled, dio will throw a error with this type.
? ? ? print("請(qǐng)求取消");
? ? }else {
//DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
? ? ? print("未知錯(cuò)誤");
? ? }
}
/*
? * 取消請(qǐng)求*
? * 同一個(gè)cancel token 可以用于多個(gè)請(qǐng)求湾盗,當(dāng)一個(gè)cancel token取消時(shí)伏蚊,所有使用該cancel token的請(qǐng)求都會(huì)被取消。? * 所以參數(shù)可選*/
? void cancelRequests(CancelToken token) {
token.cancel("cancelled");
? }
}