RCurl在出错时获得响应主体

时间:2014-11-13 16:24:44

标签: r rcurl responsetext

我只是在使用RCurl发布请求失败时尝试获取响应正文。当我通过R运行它时,我只得到响应错误并且它失败了。

Error: Unprocessable Entity

当我使用UI界面发布相同的请求进行测试时,它会给出

{
"reason": [
    "Can not create Data with Name: DataTest. Data Name should be unique."
],
"singleReason": "Can not create Data with Name: DataTest. Data Name should be unique."
}

如何获得有关4XX错误的响应机构的任何帮助表示赞赏。 TIA。

发布请求

postdata.json <- '{"name":"DataTest","description":"Test Payload","algorithm":{"name":"DataTest","version":"0.1.0"}}'
post.result <- httpPOST(url=SERVER, postfields = postdata.json, verbose = T,
                        httpheader=c(Authorization=access.token, 'Content-Type'='application/json', Accept='application/json'))

RStudio输出

* About to connect() to SERVER port 80 (#0)
*   Trying SERVER... * connected
* Connected to SERVER port 80 (#0)
> POST /api/test HTTP/1.1
Host: SERVER
Authorization: AUTHENTICATION
Content-Type: application/json
Accept: application/json
Content-Length: 171

< HTTP/1.1 422 Unprocessable Entity
< Content-Type: application/json;charset=UTF-8
< Date: Thu, 13 Nov 2014 16:31:42 GMT
< Server: Apache-Coyote/1.1
< Content-Length: 215
< Connection: keep-alive
< 
* Connection #0 to host SERVER left intact
 Show Traceback

 Rerun with Debug
 Error: Unprocessable Entity 

n.b。我很好,它失败并返回错误。这是预期的。我只是想让响应体与错误代码相关联。

2 个答案:

答案 0 :(得分:2)

这是httr的一种方法:

library(httr)

postdata.json <- '{"name":"DataTest","description":"Test Payload","algorithm":{"name":"DataTest","version":"0.1.0"}}'

res <- POST(SERVER, 
  body = postdata.json, 
  add_headers(
    Authorization = access.token, 
    'Content-Type' = 'application/json', 
    Accept = 'application/json'
  )
)

http_status(res)
content(res)

答案 1 :(得分:0)

通过添加basicTextGatherer()和writefunction,我能够使用RCurl获取响应体。

 reader <- basicTextGatherer()  
 post.result <- httpPOST(url=SERVER, postfields = postdata.json, verbose = T, 
                         writefunction = reader$update,
                         httpheader=c(Authorization=access.token, 
                                      'Content-Type'='application/json', 
                                      Accept='application/json')
                        )
 return(body=reader$value())

但是Hadley的解决方案更易于使用并且不会出错。