Ошибка API Bing Maps Distance Matrix: 'content: этот параметр отсутствует или недействителен.' - PullRequest
0 голосов
/ 09 апреля 2020

Я пробовал примеры того, как использовать API Bing's Map Distance Matrix API.
Пример был взят "как есть" с их сайта ( здесь ).

Оба примеры get и post завершаются с ошибками:

{'authenticationResultCode': 'ValidCredentials',
 'brandLogoUri': 'http://dev.virtualearth.net/Branding/logo_powered_by.png',
 'copyright': 'Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.',
 'errorDetails': ['One or more parameters are not valid.',
  'content: This parameter is missing or invalid.'],
 'resourceSets': [],
 'statusCode': 400,
 'statusDescription': 'Bad Request',
 'traceId': '338104f79bff4dfe9b18d0333e80abe7|DU00000D6A|0.0.0.0'}

и

{'authenticationResultCode': 'ValidCredentials',
 'brandLogoUri': 'http://dev.virtualearth.net/Branding/logo_powered_by.png',
 'copyright': 'Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.',
 'errorDetails': ['JSON input is incorrect'],
 'resourceSets': [],
 'statusCode': 400,
 'statusDescription': 'Bad Request',
 'traceId': 'cbef56289d164cc1a691ad8f328e4cf3|DU00000B71|0.0.0.0'}   

Запросы выполняются в Python с библиотекой 'questions'. Вот пример вызова для запроса на получение:

url = "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins=47.6044,-122.3345;47.6731,-122.1185;47.6149,-122.1936&destinations=45.5347,-122.6231;47.4747,-122.2057&travelMode=driving&key={myKeyHere}"
r = req.post(url)
j = r.json()

и это почтовый запрос:

url = "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?key={myKeyHereWithNoBrackets}"
headers = {
    "Content-Type":"application/json",
}
payload ={
    "origins": [{
        "latitude": 47.6044,
        "longitude": -122.3345
    },
    {
        "latitude": 47.6731,
        "longitude": -122.1185
    },
    {
        "latitude": 47.6149,
        "longitude": -122.1936
    }],
    "destinations": [{
        "latitude": 45.5347,
        "longitude": -122.6231
    }, 
    {
        "latitude": 47.4747,
        "longitude": -122.2057
    }],
    "travelMode": "driving"
}
response = req.post(url,headers=headers, data=payload)
json_obj = response.json()
json_obj

Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 10 апреля 2020

Я также столкнулся с подобной проблемой. Даже опубликовал похожий вопрос несколько часов назад. Следующий код работает для отправки запроса для одного источника в один пункт назначения.

import requests
import json

payload = {
    "origins": [{"latitude": 26.488991, "longitude": 80.263585}],
    "destinations": [{"latitude": 26.761714, "longitude": 80.885623}],
    "travelMode": "driving",
}

paramtr = {"key": "YOUR_KEY_GOES_HERE"}

r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = 
json.dumps(payload), params = paramtr)

print(r.json())

Ниже был ответ

{'authenticationResultCode': 'ValidCredentials',
 'brandLogoUri': 'http://dev.virtualearth.net/Branding/logo_powered_by.png',
 'copyright': 'Copyright © 2020 Microsoft and its suppliers. All rights reserved. This 
API cannot be accessed and the content and any results may not be used, reproduced or 
transmitted in any manner without express written permission from Microsoft 
Corporation.',
 'resourceSets': [{'estimatedTotal': 1,
   'resources': [{'__type': 
'DistanceMatrix:http://schemas.microsoft.com/search/local/ws/rest/v1',
     'destinations': [{'latitude': 26.761714, 'longitude': 80.885623}],
     'errorMessage': 'Request completed.',
     'origins': [{'latitude': 26.488991, 'longitude': 80.263585}],
     'results': [{'destinationIndex': 0,
       'originIndex': 0,
       'totalWalkDuration': 0,
       'travelDistance': 85.961,
       'travelDuration': 80.217}]}]}],
 'statusCode': 200,
 'statusDescription': 'OK',
 'traceId': 'b094c60cdd6e48cbad66e47b85696123|HK00000C14|0.0.0.0|HK00000A3C, 
HK00000882'}

Надеюсь, это поможет. Я до сих пор не понимаю полный лог c за ним. Если кто-то знает, пожалуйста, прокомментируйте. Рад учиться.

0 голосов
/ 09 апреля 2020

Хорошо, я решил это. При выполнении запроса POST с content-type:application/json мы должны преобразовать полезную нагрузку в json. Для этого я изменил следующую строку:

response = req.post(url, headers=headers, data=payload)

на следующую:

response = req.post(url, headers=headers, data=json.dumps(payload))

На самом деле я также должен импортировать библиотеку json.

Для запроса GET я все еще не уверен, что делать. Если кто-то знает, пожалуйста, прокомментируйте обновленный ответ или оставьте свой собственный ответ.

...