我使用R httr POST函数向jSON发送一个API。 API正确地返回一个302:Found消息,但httr正在退出该函数,然后我才能抓住响应的主体(这是一个jSON主体,有一些关键的信息)。
使用Verbose()参数运行httr,以下是响应:
; - HTTP / 1.1 302 Found < - Cache-Control:no-cache < - Pragma:no-cache < - Content-Length:47 < ; - Content-Type:application / json; charset = utf-8 < - Expires:-1 函数中出现错误(类型,msg,asError = TRUE):不能进行必要的数据回退我已经从终端运行相同的cURL文章,并且可以确认我发送的是从API产生回复302和所需的身体。
为了参考,我的R代码如下。 (注意:y是jSON格式的主体)
POST(https:// thewebsite,authenticate(myusername mypassword,type =basic), add_headers(Content-Type=application / json), body = y,verbose())有关如何绕过错误并捕获302消息内容的任何想法?
解决方案我刚刚花了一些时间与这个问题自己。问题出在HTTP规范(这基本上是RCurl坚持)和什么浏览器实际上做的不同。
事件的顺序是这样:
解决方案很简单 - 禁用以下重定向与 config(followlocation = 0L):
POST(https:// thewebsite, authenticate(myusername,mypassword), content_type_json(), config(followlocation = 0L), body = y,) b $ b#PS with httr 0.4你可以简化为 POST(https:// thewebsite, authenticate(myusername,mypassword), config(followlocation = 0L ), body = x,encode =json)然后需要查看位置字段的内容,并自己执行重定向。
有关基本问题的更多讨论,请参阅:
- HTTP:POST请求接收到302,如果重定向请求为GET?
- programmers.stackexchange/questions/99894
I'm using the R httr POST function to send a body of jSON to an API. The API is, properly, returning a 302: Found message, but httr is exiting the function before I'm able to grab the body of response (which is a jSON body, with some key bits of info.)
Running httr with the Verbose() argument, the following is the response:
<- HTTP/1.1 302 Found <- Cache-Control: no-cache <- Pragma: no-cache <- Content-Length: 47 <- Content-Type: application/json; charset=utf-8 <- Expires: -1 Error in function (type, msg, asError = TRUE) : necessary data rewind wasn't possibleI've run the same cURL post from terminal, and can confirm what I'm sending produces a reply from the API with both the 302 and the desired body.
For reference my R code follows. (note: y is the jSON formatted body)
POST("thewebsite",authenticate("myusername","mypassword",type="basic"), add_headers("Content-Type" = "application/json"), body = y, verbose())Any thoughts on how to bypass the error and capture the 302 message content?
解决方案I just spent some time battling with this issue myself. The problem comes down to a difference in the HTTP spec (which is basically what RCurl adheres to) and what browsers actually do.
The sequence of events is this:
The solution is simple - disable the following of redirects with config(followlocation = 0L):
POST("thewebsite", authenticate("myusername","mypassword"), content_type_json(), config(followlocation = 0L), body = y, ) # PS with httr 0.4 you can simplify to POST("thewebsite", authenticate("myusername","mypassword"), config(followlocation = 0L), body = x, encode = "json" )You'll then need to look at the contents of the location field, and do the redirect yourself.
For more discussion of the underlying issue, see:
- HTTP: POST request receives a 302, should the redirect-request be a GET?
- programmers.stackexchange/questions/99894
更多推荐
抑制302 httr POST返回的错误
发布评论