【问题标题】:Prolog http get request with request headers带有请求标头的 Prolog http get 请求
【发布时间】:2015-03-20 13:13:01
【问题描述】:

我尝试使用带有 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() 来完成。

【问题讨论】:

    标签: json prolog swi-prolog


    【解决方案1】:

    如果您想指定 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

    【讨论】:

    • 感谢 Wouter 提供的代码示例。我没有在您的示例中看到将 X-Mashape-Key 指定为请求标头,我认为这是获取 Json 响应所必需的。我将查看 SWI7 字典,我使用的是版本 7。另外感谢您打开有关 SSL 身份验证的票证,期待有关该问题的答案。
    • 刚刚看到ticket上关于SSL认证的答案,SSL证书看起来还可以,可能是因为请求头中没有指定mashape key?
    猜你喜欢
    • 2011-09-20
    • 2015-02-22
    • 2015-08-20
    • 2018-11-29
    • 2013-08-03
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多