【发布时间】:2019-10-29 17:32:39
【问题描述】:
我在 Flutter 中的 Http Post 请求遇到了一些问题。我必须连接到 PHP Web 服务(使用标头)并发布一些用户/密码信息以获得响应(此处为用户信息)。
我相信我已经接近解决方案,但我仍然收到StatusCode 401 作为回复,尽管当我尝试使用 Postman(使用相同的凭据)时它可以工作。
这是我调用的函数的代码:
Future<http.Response> post() async {
var url = "https://www.monadresse/login.php";
String password = "xxx";
String username = "yyy";
//var bytes = utf8.encode("$username:$password");
var bytes = "$username:$password";
String userNameUser = "www";
String passwordUser = "zzz";
var passwordUserEncoded = base64.encode(utf8.encode(passwordUser));
//var passwordUserEncoded = base64.encode(passwordUser);
var headers = {
"Authorization": "Basic $bytes",
"Content-Type": "application/json",
};
var requestBody = json.encode({ 'user': userNameUser, 'password': passwordUserEncoded});
print(headers);
print(requestBody);
final http.Response response = await http.post(
url,
body: requestBody,
headers: headers,
);
if(response.statusCode == 200){
var responseJson = json.decode(response.body);
print(Utf8Codec().decode(response.bodyBytes));
print("Body: " + responseJson);}
print(bytes);
print(passwordUserEncoded);
print(response.statusCode);
print("Fini");
}
另一件奇怪的事情(读作“我不明白”)...我添加了一些打印件以了解正在发生的事情,正如您在下文中看到的那样,前 2 个打印件(位于请求之前)是第一次打印两次,然后最后 3 次打印也重复两次。
flutter: {Authorization: Basic yyy:xxx, Content-Type: application/json}
flutter: {"user":"www","password":"zzz"}
flutter: {Authorization: yyy:xxx, Content-Type: application/json}
flutter: {"user":"www","password":"zzz}
flutter: yyy:xxx
flutter: zzz
flutter: 401
flutter: Fini
flutter: yyy:xxx
flutter: zzz
flutter: 401
flutter: Fini
由于我在网上找不到解决方案,我非常希望有人能帮助我。
【问题讨论】:
-
你需要utf8编码,然后base 64编码username:password字符串。
-
感谢理查德的回答!我尝试使用 utf8encode - base64 但也没有说话......我会搜索你的答案,现在没有时间......
-
谢谢理查德 它有效!我不知道标头必须是 utf8-base64 编码(我之前尝试过,但顺序错误)
-
一般情况下,标题不会。基本认证头的形式为:Authorization -> Basic AAAAAAAAA,其中AAAAAA是username:password在utf8中的base64编码。 (请注意 Basic 一词是如何以纯文本形式出现的。