dart Flutter终端测试中HTTP POST请求

vbopmzt1  于 2023-09-28  发布在  Flutter
关注(0)|答案(1)|浏览(134)

我试图在我的flutter应用程序在我的终端测试我的后端端点,我不知道如何去做它这里的

Future loginUserWithUsernameAndPassword(
String userName, String password) async {
 Map loginInfo = {
"userName": userName,
"password": password,
};

 var body = json.encode(loginInfo);

String url = baseUrl;

return await http.post(Uri.parse(url), body: body).then(
  (value) {
  return json.decode(value.body);
},
);
}

 void main() async {
print(await loginUserWithUsernameAndPassword("sparky", "password"));
}

我不确定在终端输入什么使它运行我尝试什么都不起作用

nx7onnlm

nx7onnlm1#

试试这个:

import "package:http/http.dart" as http;

Future<void> main() async {
  final String responseBody = await loginUserWithUsernameAndPassword(
    username: "kminchelle",
    password: "0lelplR",
  );
  print(responseBody);
}

Future<String> loginUserWithUsernameAndPassword({
  required String username,
  required String password,
}) async {
  const String baseUrl = "https://dummyjson.com/auth/login"; // Replace with your API Base URL
  final Uri uri = Uri.parse(baseUrl);
  final http.Response response = await http.post(
    uri,
    body: <String, dynamic>{
      "username": username,
      "password": password,
    },
  );
  return Future<String>.value(response.body);
}

输出量:

flutter: {"id":15,"username":"kminchelle","email":"[email protected]","firstName":"Jeanne","lastName":"Halvorson","gender":"female","image":"https://robohash.org/autquiaut.png","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsInVzZXJuYW1lIjoia21pbmNoZWxsZSIsImVtYWlsIjoia21pbmNoZWxsZUBxcS5jb20iLCJmaXJzdE5hbWUiOiJKZWFubmUiLCJsYXN0TmFtZSI6IkhhbHZvcnNvbiIsImdlbmRlciI6ImZlbWFsZSIsImltYWdlIjoiaHR0cHM6Ly9yb2JvaGFzaC5vcmcvYXV0cXVpYXV0LnBuZyIsImlhdCI6MTY5NTEwNTg1NywiZXhwIjoxNjk1MTA5NDU3fQ.9ckMNZFS2nAYNjrFUJhZt-nUcpJzNGkdn9AmIPGoK5Q"}

相关问题