flutter 发送http请求时如何实现try语句?

dly7yett  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(205)

我想创建一个登录方法来发布http request。我使用以下代码将用户数据发布到服务器并获得响应:

import 'dart:convert';
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../Services/baseHttp.dart' as base;

class Services {
  late var token = '';

  Future<http.Response> login(String username, String password) async {
    var url = base.BaseURL.loginUrl;
    Map data = {"username": username, "password": password};
    var body = json.encode(data);
    var response = await http.post(Uri.parse(url),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: body);

    print(response.statusCode);
    token = response.body;
    print(token);
    return response;
  }
}

我试着在方法里面使用try catch

Future<http.Response> login(String username, String password) async {
try {
    var url = base.BaseURL.loginUrl;
    Map data = {"username": username, "password": password};
    var body = json.encode(data);
    var response = await http.post(Uri.parse(url),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: body);

    print(response.statusCode);
    token = response.body;
    print(token);
    return response;
    } catch (e) {
      print(e);
    }
}

我想在抛出任何异常时发送statusCode而不是print(e)。我该怎么做呢?

5lhxktic

5lhxktic1#

要检查响应是否有效,可以检查状态代码是否等于200,如下所示:

if (response.statusCode == 200){
// Do something
} else {
// Throw exception
}

查看官方文档。您将看到以下内容:

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

相关问题