【问题标题】:Authentication credentials with Rest API使用 Rest API 的身份验证凭据
【发布时间】:2021-07-03 09:21:10
【问题描述】:

我正在尝试检索可通过 Rest API 访问的信息。但我不确定如何通过身份验证凭据。

GET 端点没有任何地方可以插入用户名和密码。

当我尝试通过浏览器获取此信息时,它会要求提供凭据。 但是如何使用 python 调用 GET 请求并传递登录服务器所需的凭据?

Here is how it looks via browser

@编辑 好的,这就是我发现的:

它适用于 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

这给了我一个正确的回应:

serial    : <string>
name      : <string>
timestamp : 20210422114954
in        : 6
out       : 6

但是我如何将它翻译成 python? 我已经试过了:

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)

但响应总是:

<Response [401]>

【问题讨论】:

  • 你能展示你的代码吗?
  • 这能回答你的问题吗? Python, HTTPS GET with basic authentication
  • 很可能是在使用 HTTPBasic Auth。取决于您尝试连接的方式将取决于您如何设置标题
  • 好吧,我了解了有关 HTTPBasic Auth 的更多信息,但它不适用于我的情况。这是我的代码:import requests from requests.auth import HTTPBasicAuth response = requests.get('http://&lt;server ip&gt;:8080/local/people-counter/.api?live-sum.json', auth=('user', 'password')) print(response) 但它返回 401,这很奇怪,因为当我通过浏览器使用相同的凭据时它可以工作......

标签: python powershell rest


【解决方案1】:

您可以使用HTTP Client

她的更多: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);
}

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2020-08-21
    • 2018-07-26
    • 1970-01-01
    • 2017-11-22
    • 2015-05-16
    • 2019-04-29
    • 2015-01-10
    • 1970-01-01
    相关资源
    最近更新 更多