Power Query,使用表单数据发出 http POST 请求
Posted
技术标签:
【中文标题】Power Query,使用表单数据发出 http POST 请求【英文标题】:Power Query, make http POST request with form data 【发布时间】:2018-05-03 09:47:50 【问题描述】:我有一个 REST API,它只接受带有表单数据的 POST 请求。
我知道在 Power Query 中 JSON 请求是这样的:
let
url = "https://example.com",
body = " ""first_param"": ""AAAAA"", ""second_param"": ""BBBBBB""",
Source = Json.Document(Web.Contents(url,[ Headers = [#"Content-Type"="application/json"], Content = Text.ToBinary(body) ] ))
in
Source
如何发送表单数据??
【问题讨论】:
经过一些简短的谷歌搜索后,来自表单的 POST 请求以“application/x-www-form-urlencoded”或“multipart/form-data”格式在正文中发送。因此,我会查找如何生成您的数据以匹配其中一种格式,并将其放入 Web.Contents 请求的 Content 参数中。 【参考方案1】:使用 Uri.BuildQueryString 和 Json.Document
let
url = "https://example.com",
body = " ""first_param"": ""AAAAA"", ""second_param"": ""BBBBBB""",
Parsed_JSON = Json.Document(body),
BuildQueryString = Uri.BuildQueryString(Parsed_JSON),
Source = Json.Document(Web.Contents(url,[Headers = [#"Content-Type"="application/json"], Content = Text.ToBinary(BuildQueryString) ] ))
in
Source
顺便说一句,你最好将body
直接构造成record
,避免文本字符串和双引号)
【讨论】:
您能否解释一下如何在正文中传递当前日期?就我而言,我将 fromDate 和 toDate 作为 first 和 second 参数。DateTime.LocalNow()
等于 2013-03-08T14:22:42
或者类似= DateTime.ToText(DateTime.LocalNow(), "yyyy-MM-dd")
等于2018-08-29
【参考方案2】:
我使用这种方式工作,授权类型是基本和编码的用户名和密码。
let
url = "http://localhost:8091/_p/query/query/service?",
body = "
""statement"": ""SELECT ROUND((SUM(src.DUR) / COUNT(.)), 0) AS 'Mean Screen Time per day' FROM \r\n(SELECT
SUM(TONUMBER(source.DURATION)) AS DUR, source.startDate AS DATE FROM \r\n(SELECT startDate, DATE_DIFF_STR(completionDate,
startDate, 'second') AS DURATION, attributes.screen AS SCREEN \r\nFROM data WHERE type_ = \""Event\"" AND type is NOT MISSING and
startDate IS NOT MISSING and completionDate IS NOT MISSING \r\nand completionDate > startDate and attributes.screen IS NOT
MISSING) source GROUP BY source.startDate) src"",
""pretty"":true,""timeout"":""600s"",""profile"":""timings"",""scan_consistency":"not bounded"",""client_context_id"":""xyz""",
Source = Json.Document(Web.Contents(
url,[
Timeout=#duration(0,0,120,0),
Headers=[#"Authorization"="Basic YXB",#"Content-Type"="application/json"],
Content=Text.ToBinary(body)
]
)
),
results = Source[results],
#"Converted to Table" = Table.FromList(results, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
#"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", "MEAN _DURATION", "SCREEN","MEAN DURATION","SCREEN"),
#"Changed Type" = Table.TransformColumnTypes(#"Expanded Column1","MEAN_DURATION", type number)
in
#"Changed Type"
【讨论】:
我认为如果您将此代码编写为代码块作为答案会更有用。这将有助于将来其他用户测试您的答案。 你确定 :) @Mr.D以上是关于Power Query,使用表单数据发出 http POST 请求的主要内容,如果未能解决你的问题,请参考以下文章