我尝试使用带有prolog的请求标头进行http get请求,但我无法找到如何做到这一点。
以下是如何在Python中执行此操作的示例:
response = unirest.get("https://poker.p.mashape.com/index.php?players=3",
headers={
"X-Mashape-Key": "mykey",
"Accept": "application/json"
}
此请求的响应在Json中,如下所示:
{
"player_cards": {
"1": [
"Jh",
"4c"
],
"2": [
"3s",
"Js"
],
"3": [
"3d",
"5c"
],
"4": [
"Kh",
"Qs"
]
},
"showdown": [
"Ks",
"6h",
"4s",
"Ac",
"9h"
],
"winning_hands": {
"1": [
"4c",
"4s",
"Ac",
"Ks",
"Jh"
],
"2": [
"Ac",
"Ks",
"Js",
"9h",
"6h"
],
"3": [
"Ac",
"Ks",
"9h",
"6h",
"5c"
],
"4": [
"Kh",
"Ks",
"Ac",
"Qs",
"9h"
]
},
"winners": [
4
]
}
我的序言
poker(Players) :-
format(atom(HREF),'https://poker.p.mashape.com/index.php?players=~s',[Players]),
http_get(HREF,Json,[]),
如何在此处指定http get请求标头以及如何存储和使用Json结果?该函数必须打印Json结果,我知道这可以通过writeln()完成。
答案 0 :(得分:3)
我想指定HTTP请求标头,我建议使用http_open/3
i.o. http_get/3
。例如:
:- use_module(library(http/http_open)).
:- use_module(library(http/json)).
poker(Dict):-
setup_call_cleanup(
http_open('https://poker.p.mashape.com/index.php?players=3', In, [request_header('Accept'='application/json')]),
json_read_dict(In, Dict),
close(In)
).
请注意我使用setup_call_cleanup/3
。这可确保即使中间的代码失败或引发异常,流也会关闭。
json_read_dict/2
会返回SWI7 dictionary。你需要SWI-Prolog版本7!最好是the development branch的最新提交。
您使用的URI似乎需要SSL身份验证。我相信也可以在SWI-Prolog中使用它,但我找不到如何执行此操作的示例。请参阅my question to the SWI-Prolog mailinglist。