我正在尝试从REST API访问JSON数据(在R中)。
要验证自己的身份,我需要在https://dashboard.server.eu/login中使用POST方法。需要发送的数据是电子邮件和密码:
library(httr)
login <- list(
email = "[email protected]",
password = "mypass"
)
res <- POST("https://dashboard.server.eu/login", body = login, encode = "form", verbose())
执行以上操作时,我得到以下输出:
-> POST /login HTTP/1.1
-> Host: dashboard.server.eu
-> User-Agent: libcurl/7.59.0 r-curl/3.3 httr/1.4.1
-> Accept-Encoding: gzip, deflate
-> Cookie: session=10kq9qv1udf0107F4C70RY14fsum41sq50
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Type: application/x-www-form-urlencoded
-> Content-Length: 53
->
>> email=my%40email.com&password=mypass
<- HTTP/1.1 200 OK
<- access-control-allow-headers: Accept, Authorization, Content-Type, If-None-Match
<- access-control-allow-methods: HEAD, GET, POST, PUT, DELETE
<- cache-control: no-cache
<- content-encoding: gzip
<- content-type: application/json; charset=utf-8
<- date: Mon, 09 Mar 2020 14:58:31 GMT
<- set-cookie: session=10kq9qv1udf0107F4C70RY14fsum41sq50; HttpOnly; SameSite=Strict; Path=/
<- vary: origin,accept-encoding
<- x-microserv: NS4yNi4xODQuMjE3
<- x-poweredby: Poetry
<- Content-Length: 2346
<- Connection: keep-alive
该网站的文档说,如果成功,将res
返回JSON并在中包含一个字符串令牌res.data._id
。
我找不到它,即使查看的每个列表(和子列表)res
。
我应该如何找到令牌?
遵循该文档以及AngularJS中的示例,然后我应该这样做:
// Create JSON Object with your token
let authorizeObject = {
'Authorization': 'Session ' + token,
'content-type': 'application/json;charset=UTF-8',
'accept': 'application/json,text/plain',
};
// Create header from the previous JSON Object
let header = {'headers':authorizeObject};
// Use the header in your http request...
$http.get('https://dashboard.server.eu/', header)
关于实现这个梦想的任何暗示?
更新-使用cURL,我可以检查是否_id
返回了键/值…
使用命令:
curl -k -X POST "https://dashboard.server.eu/login" \
-d '{ "email" : "[email protected]", "password" : "mypass" }' \
-H "Content-Type: application/json"
我得到的输出:
{
"_id": "697v2on4ll0107F4C70RYhosfgtmhfug",
"isAuthenticated": true,
"user": {
"_id": "5dd57868d83cfc000ebbb273",
"firstName": "me",
"lastName": "Me",
...
因此,会话令牌确实在某处...
这对我有帮助吗?
查看问题中的图像res
,该消息就在下面content
-仅是将内容存储为原始字节的向量,这就是为什么您不将其识别为json的原因。
由于http可以发送任何文件类型,因此httr
出于各种原因,响应对象中的内容以原始格式而不是字符串存储-也许最重要的是,因为许多二进制文件将包含一个0x00
字节,而这是字符所不允许的R中的字符串。
在你的情况,我们不仅可以告诉大家,res$content
是文字,但它是你的“失踪” JSON。的前六个字节res$content
显示在图像中,分别为7b, 22, 5f, 69, 64, 22
。我们可以通过以下操作将它们转换为R中的字符串:
rawToChar(as.raw(c(0x7b, 0x22, 0x5f, 0x69, 0x64, 0x22)))
[1] "{\"_id\""
这与预期的json字符串的前六个字符匹配。
因此,如果您这样做:
httr::content(res, "text")
要么
rawToChar(res$content)
您将以字符串形式获取json。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句