我想创建一个登录方法来发布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)
。我该怎么做呢?
1条答案
按热度按时间5lhxktic1#
要检查响应是否有效,可以检查状态代码是否等于200,如下所示:
查看官方文档。您将看到以下内容: