Question

I'm trying to convert the following curl command into httr/RCurl to get a cookie into R. But I'm not sure how to pass the data "j_username=username&j_password=password" using getURL(...) or GET(...)

curl --data "j_username=username&j_password=password" http://localhost:8080/myApp/j_spring_security_check --cookie-jar cookies.txt

I'm able to get the cookie information created by command line curl command above and paste it into the GET request (it works). If I could generate the cookie within R it would be convenient.

Here's my working httr get GET():

GET(dataURL,
   verbose(),
   add_headers("Content-type"="application/json",
               "Accept"="application/json",
               "Accept-Version"=" 1.0",
               "Cookie"="JSESSIONID=24BA7A80A02317AD2B6C87C8D10B6787"
               )
    )
Was it helpful?

Solution

It's hard to tell without a reproducible example, but I think the httr code you want is this:

library(httr)
baseUrl <- "http://localhost:8080/myApp/"

POST(baseUrl, path = "j_spring_security_check", 
  body = list(j_username = "username", j_password = "password"),
  multipart = FALSE,
  verbose()
)

headers <- add_headers(
  "Content-Type" = "application/json", 
  Accept = "application/json",
  "Accept-Version" = "1.0"
)

GET(baseUrl, headers, verbose())

httr automatically sets up the handle to preserve cookies within a domain.

OTHER TIPS

Using the following link I was able to authenticate and get data from REST: [How to use RCurl to authenticate to spring security / grails app

Here's a snippet of my code to help anyone else that might run into this issue:

require(RCurl)
require(RJSONIO)

baseUrl = "http://localhost:8080/myApp/"
authenticateUrl = paste(baseUrl, "j_spring_security_check", sep="")

curl = getCurlHandle()
curlSetOpt(ssl.verifypeer=FALSE, timeout=60, cookiefile="cookies.txt",   
           cookiejar="cookies.txt", 
           followlocation = TRUE, curl=curl, verbose=verbose
          )

loginUrl = paste(baseUrl, "login/auth", sep="")

getURL(loginUrl, curl=curl)

postForm(authenticateUrl, .params= list(j_username="username", j_password="password"),    
                 curl=curl, style="POST")

getResponse <- getURL(baseUrl,
               httpheader=c("Content-Type"="application/json",
                            Accept="application/json",
                           "Accept-Version"=" 1.0"),
               curl=curl)

... 

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top