http - Http POST 请求以 base64 编码的 json 形式返回正文
问题描述
具有授权的 eXist-db POST 请求给出包含 2 个项目的响应。第一个是标题,第二个是不可见的。当我把它放在 string() 函数中时,它显示为包含 json 的 base64 二进制字符串。Json 是连接到 API 发送授权数据的格式默认类型(并且可能是唯一的一种)。
我试图检查 eXist 是否添加了某些标头,但似乎没有任何问题。使用请求捕获器并获得该数据:
OST / HTTP/1.1
Host: endpoint.requestcatcher.com
Accept-Encoding: gzip,deflate
Authorization: Basic OWJhMT...
Connection: Keep-Alive
Content-Length: 0
Content-Type: code
Status-Only: false
User-Agent: Apache-HttpClient/4.5.5 (Java/12.0.1)
这是我的功能代码:
declare function auth:get-access-token() {
let $accessTokenResponse :=
hc:send-request(<hc:request method = 'post' href='https://endpoint.requestcatcher.com'>
<hc:header name = 'Authorization' value = 'Basic { $auth:base64credentials }'/>
<hc:header name = 'status-only' value = 'false'/>
</hc:request>)
return $accessTokenResponse
};
实际结果是响应正文包含包含 json 数据的 base64 编码字符串。
我想接收最初由 API 授权端点发送的 json 数据。
解决方案
如果您知道您的 API 返回 JSON,您可以处理 Base64 编码的响应主体,只需将其传递给util:binary-to-string()
,然后假设您想要解析的 JSON 而不是原始文本,然后将其传递给fn:parse-json()
.
这是显示一些用于处理响应的附加逻辑的示例代码。一些备注:
- 我正在使用返回 JSON 的示例端点。
- 它检查响应以确保 200 响应;如果不是,它只返回状态和消息作为地图。
- 它处理EXPath HTTP 客户端规范中概述的各种响应正文类型的情况。
- 它对解析 JSON 的 JSON 主体采取了额外的步骤。
编码:
xquery version "3.1";
import module namespace http = "http://expath.org/ns/http-client";
let $url := "https://jsonplaceholder.typicode.com/todos/1"
let $response := http:send-request(<http:request method = "get" href="{$url}"/>)
let $head := $response[1]
let $body := $response[2]
let $media-type := $head/http:body/@media-type => tokenize("; ") => head()
return
if ($head/@status eq "200") then
(: When the response body contains XML or HTML, it is parsed into a document node. :)
if ($body instance of document-node()) then
$body
(: When the media type is text/*, convert the Base64Binary body to string :)
else if (starts-with($media-type, "text/")) then
$body => util:binary-to-string()
(: Parse JSON into XDM :)
else if ($media-type eq "application/json") then
$body => util:binary-to-string() => parse-json()
(: Assume the body is just binary :)
else
$body
else
map {
"status": $head/@status => string(),
"message": $head/@message => string()
}
我的系统上的响应:
map {
"userId": 1.0e0,
"completed": false(),
"title": "delectus aut autem",
"id": 1.0e0
}
解析 JSON 的好处是您可以查询结果,例如,$result?title
将返回"delectus aut autem"
.
推荐阅读
- php - 如何在短代码中获取帖子网址
- javascript - javascript selection text change font size code editor
- c# - 将类实例保存到文件并从另一个项目访问它
- css - 使用数据库中的数据制作可滚动的引导表
- php - Laravel 将数据库整数转换为字符串
- java - 如何在 install4j 中禁用箭头屏幕导航
- android - Angular 4 逗号不适用于平板电脑 android 键盘
- firefox - svg.node.getScreenCTM() 在 Firefox 中不可用
- amazon-web-services - 修改表后从 AWS AURORA 触发 AWS lambda
- ionic-framework - ion-footer 中的 ion-fab 总是在 ion-content 下