Search code examples
rspring-securityrcurlrscripthttr

Cookie request using R


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"
               )
    )

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.