I use the command line tool curl to post data and get response from server, the command is like this:
curl -X POST -H 'Content-Type: application/gpx+xml' -H 'Accept: application/json' --data-binary #gpslog.gpx "http://test.roadmatching.com/rest/mapmatch/?app_id=MY_APPID&app_key=MY_APPKEY" -o output.json
I tried using RCurl package to do the same thing, but it doesn't work. Can someone point me to the right direction? Thanks.
postForm(uri = "http://test.roadmatching.com/rest/mapmatch/?app_id=MYID&app_key=MYKEY",
.ops = list(httpheader = c('Content-type': 'application/gpx','Accept': 'application/json')),
.params = "/Users/data.gpx")
With httr - not tested, you may have to tweak it a bit
url <- "http://test.roadmatching.com/rest/mapmatch"
args <- list(app_id = "MY_APPID", app_key = "MY_APPKEY")
gpxxml <- add_headers(`Content-Type` = "application/gpx+xml")
httr::POST(url, query = args, gpxxml, accept_json(),
write_disk("output.json"), body = upload_file("gpslog.gpx"))
Related
I want to create an R script to use instead of a curl request.
Using curl, I use a Google API which requires the --data option. I am not sure how to add this option to my curl request using the curl package.
The request that works using Git Bash is as follows:
API_KEY="[xyz]"
curl "https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=$API_KEY" \
--header 'Content-Type: application/json' \
–-data '{"url": "https://www.example.com/"}'
This is my R code, which doesn't send the necessary URL to return anything good:
library(curl)
API_KEY = "xyz"
h <- new_handle()
handle_setheaders(h,
"Content-Type" = "application/json"
)
r <- curl_fetch_memory(url = paste0("https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=",API_KEY), h)
So how can I add the --data option using the curl package?
You can use the lower-level curl if you really want to. In this case your original CURL command is performing a POST action with a JSON encoded body. The equivalent of that in the R curl library would be
library(curl)
API_KEY <- "xyz"
url <- paste0("https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=", API_KEY)
payload <- charToRaw('{"url": "https://www.example.com/"}')
h <- new_handle()
handle_setopt(h, post=TRUE, postfields=payload)
handle_setheaders(h, "Content-Type" = "application/json")
r <- curl_fetch_memory(url = url, h)
cat(rawToChar(r$content))
I am trying to read a json from an authenticated API using R, but not sucessfully.
I have the Curl code and tried to convert it to R using "curlconverter" library and also tried to get it using "httr" library.
curl -X GET \
'https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1' \
-H 'Cache-Control: no-cache' \
-H 'x-glb-token: mytoken'
I would appreciate a solution to write this code in R.
library(curlconverter) # devtools::install_github("hrbrmstr/curlconverter")
u <- "curl -X GET 'https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1' -H 'Cache-Control: no-cache' -H 'x-glb-token: mytoken'"
straighten(u) %>%
make_req()
That makes:
httr::VERB(verb = "GET", url = "https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1",
httr::add_headers(`Cache-Control` = "no-cache",
`x-glb-token` = "mytoken"))
which very straightforwardly (if one has done any research before posting a question) translates to:
httr::GET(
url = "https://api.cartolafc.globo.com/auth/liga/gurudocartola-com",
httr::add_headers(
`Cache-Control` = "no-cache",
`x-glb-token` = "mytoken"
),
query = list(
`orderBy` = "campeonato",
`page` = 1L
)
)
The back-ticks are there solely to remind me they are parameters (and, they sometimes contain dashes or other chars which force a back-tick quote).
This is, I presume, some really simple curl code that I am trying to translate into a httr format.
curl -X POST \
--user '<email>:<password>' \
--header 'user-key: <user_key>' \
--url https://api.m.com/v1/clients
So far I have tried
library(httr)
POST(url = "https://api.m.com/v1/clients",
add_headers('user-key' = "userkey",
user = 'email:password'))
But without success. Any hints on what is wrong here? Is there an httr equivalent to --user in the curl code?
library(httr)
username <- 'my_user_name'
password <- 'my_password'
POST(url = "https://api.m.com/v1/clients",
config = authenticate(username, password), add_headers("Content-Type: application/json"),
body = upload_file('./my_file.json'),
encode = 'json')
I would like to move the following curl call to Rcurl:
curl 'http://myserver.org/stream'
-H 'Authorization: Basic XXXXXXXX' -H 'Connection: keep-alive' --data-binary '{"limit": 20}'
-H 'Content-Type: application/json;charset=UTF-8'
This is one of my R tests:
library(RCurl)
url.opts <- list(httpheader = list(Authorization ="Basic XXXXXXXX",
Connection = "keep-alive",
"Content-Type" = "application/json;charset=UTF-8"))
getURLContent('http://myserver.org/stream', .opts=url.opts)
Now I am missing an attribute to add --data or --data-binary. How to add this option?
Thanks a lot
Markus
Thanks a lot #hadley.
This is my working solution:
library(httr)
user <- "test"
password <- "test123"
POST(url = 'http://myserver.org/stream',
config = c(authenticate(user, password, "basic"),
add_headers(Connection = "keep-alive"),
accept_json()),
body = "{'username':'test'}")
I want to post XML data with cURL. I don't care about forms like said in How do I make a post request with curl.
I want to post XML content to some webservice using cURL command line interface. Something like:
curl -H "text/xml" -d "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/
The above sample however cannot be processed by the service.
Reference example in C#:
WebRequest req = HttpWebRequest.Create("http://myapiurl.com/service.svc/");
req.Method = "POST";
req.ContentType = "text/xml";
using(Stream s = req.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(myXMLcontent);
}
using (Stream s = req.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
MessageBox.Show(sr.ReadToEnd());
}
-H "text/xml" isn't a valid header. You need to provide the full header:
-H "Content-Type: text/xml"
I prefer the following command-line options:
cat req.xml | curl -X POST -H 'Content-type: text/xml' -d #- http://www.example.com
or
curl -X POST -H 'Content-type: text/xml' -d #req.xml http://www.example.com
or
curl -X POST -H 'Content-type: text/xml' -d '<XML>data</XML>' http://www.example.com
It is simpler to use a file (req.xml in my case) with content you want to send -- like this:
curl -H "Content-Type: text/xml" -d #req.xml -X POST http://localhost/asdf
You should consider using type 'application/xml', too (differences explained here)
Alternatively, without needing making curl actually read the file, you can use cat to spit the file into the stdout and make curl to read from stdout like this:
cat req.xml | curl -H "Content-Type: text/xml" -d #- -X POST http://localhost/asdf
Both examples should produce identical service output.
Have you tried url-encoding the data ? cURL can take care of that for you :
curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/
You can try the following solution:
curl -v -X POST -d #payload.xml https://<API Path> -k -H "Content-Type: application/xml;charset=utf-8"