且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在Matrix Routing v8 HereMaps API上对异​​步请求进行身份验证

更新时间:2023-12-03 08:32:10

有两种身份验证方法

There are two authentication methods available to you for using HERE APIs: API key and OAuth token.

由于凭据的处理方式,当您发出异步请求时,您将需要在使用API​​密钥时禁用自动客户端重定向,因为客户端不会再次添加 apiKey 参数到已重定向到的URL.

Because of the way credentials are being handled, when you make an asynchronous request, you'll need to disable automatic client redirects when using API key, as the client will not add the apiKey parameter again to the URL it has been redirected to.

使用Python和 requests 时,有许多解决此问题的方法,下面是一个完整的示例,可能会有所帮助:

There are many solutions to this problem when using Python and requests, and here's a complete example that might help:

import requests, time

api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# "Profile mode (car fastest)" example request
request = {
    "origins": [{"lat": 52.5309, "lng": 13.3849}, {"lat": 54.0924, "lng": 12.0991}],
    "destinations": [
        {"lat": 51.3397, "lng": 12.3731},
        {"lat": 51.0504, "lng": 13.7373},
    ],
    "regionDefinition": {"type": "world"},
    "profile": "carFast",
}

# Using a Session object allows you to persist certain parameters accross requests
# see: https://requests.readthedocs.io/en/master/user/advanced/
session = requests.Session()
# Add `?apiKey=xxxxxx` to all requests
session.params = {"apiKey": api_key}
# Raise an exception for any non 2xx or 3xx HTTP return codes
session.hooks = {"response": lambda r, *args, **kwargs: r.raise_for_status()}

# Send an asynchronous request, see: https://developer.here.com/documentation/matrix-routing-api/8.3.0/dev_guide/topics/get-started/asynchronous-request.html
status_response = session.post(
    "https://matrix.router.hereapi.com/v8/matrix", json=request
).json()

# Polling for the job status for 100 times
# You might want to use exponential back-off instead of time.sleep
for _ in range(0, 100):
    # do not follow the redirect here
    status_response = session.get(
        status_response["statusUrl"], allow_redirects=False
    ).json()

    if status_response["status"] == "completed":
        # download the result
        matrix_response = session.get(status_response["resultUrl"]).json()
        print(matrix_response)
        break
    elif status_response["accepted"] or status_response["inProgress"]:
        continue
    else:
        print(f"An error occured: {status_response}")
        break
    time.sleep(0.5)  # sleep for 500 ms

免责声明:我在HERE Technologies从事矩阵路由工作.

Disclaimer: I work at HERE Technologies on Matrix Routing.