[英]Authentication credentials with Rest API
I am trying to retrive information, that is accessible via Rest API.我正在尝试检索可通过 Rest API 访问的信息。 But I am not sure how to pass authentication credentials.
但我不确定如何通过身份验证凭据。
GET endpoint doesn't have any place to insert username and password. GET 端点没有任何地方可以插入用户名和密码。
When I try to get this info through browser it asks for credentials.当我尝试通过浏览器获取此信息时,它会要求提供凭据。 But how can I call GET request with python and pass credentials that are required to log in into server?
但是如何使用 python 调用 GET 请求并传递登录服务器所需的凭据?
Here is how it looks via browser这是通过浏览器的外观
@EDIT Ok here is what I found: @EDIT 好的,这是我发现的:
It works with powershell:它适用于 powershell:
$root = 'http://<server>:8080/local/people-counter/.api?live-sum.json'
$user = "user"
$pass= "pass"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$result = Invoke-RestMethod $root -Credential $credential
$result
This gives me a proper response:这给了我一个正确的回应:
serial : <string>
name : <string>
timestamp : 20210422114954
in : 6
out : 6
But how do I translate this to python?但是如何将其翻译为 python? I already tried:
我已经尝试过:
import requests
from requests.auth import HTTPBasicAuth
response = requests.get('http://<server>:8080/local/people-counter/.api?live-sum.json', auth=HTTPBasicAuth('user', 'pass'))
print(response)
But response is always:但回应总是:
<Response [401]>
You can use HTTP Client
.您可以使用
HTTP Client
。
Her's more: https://api.flutter.dev/flutter/dart-io/HttpClient-class.html她的更多: https://api.flutter.dev/flutter/dart-io/HttpClient-class.html
import 'dart:convert';
import 'dart:developer' as developer;
import 'package:http/http.dart' as http;
main() async {
var client = http.Client();
String username = 'example';
String password = 'example123';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
String url =
'https://example.com/api';
print(basicAuth);
var response = await client.get(contacts_url,
headers: <String, String>{'authorization': basicAuth});
print(response.statusCode);
developer.log(response.body);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.