I need to run following code
library(curl)
user= "GEAS"
password= "878282193100310"
content = paste("username=", user, "&password=", password, sep="")
h <- new_handle(copypostfields = content)
handle_setheaders(h,
"Content-Type" = "application/x-www-form-urlencoded"
)
handle_setopt(h, ssl_verifypeer = FALSE, ssl_verifyhost = FALSE)
However, this code stops at line when new_handle function is applied. When running this line I have following output
> h
<curl handle> (empty)
How can I make new_handle function work properly?
Related
I am trying to post a new tweet from R using httr. But I am getting the following error:
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
I am using the following code to authorize my app using PIN-based authorization
app <- oauth_app(
app = "",
key = "CONSUMER_KEY",
secret = "CONSUMER_SECRET"
)
create_oauth_signature <- function(url, method, oauth_app, token = NULL, token_secret = NULL, private_key = NULL, ...){
httr::oauth_header(
httr::oauth_signature(
url,
method,
app = oauth_app,
token,
token_secret,
private_key,
other_params = list(...)
)
)
}
get_authorization_url <- function(app, callback, permission = NULL){
response <- POST(
url = "https://api.twitter.com/oauth/request_token",
create_oauth_signature("https://api.twitter.com/oauth/request_token", "POST", app, oauth_callback = callback)
)
stop_for_status(response)
params <- httr::content(
response,
type = "application/x-www-form-urlencoded"
)
authorization_url <- modify_url(
"https://api.twitter.com/oauth/authenticate",
query = list(
oauth_token = params$oauth_token
)
)
return(list(authorization_url, params$oauth_token))
}
get_user_oauth_token <- function(verfier_code, token){
response <- POST(
modify_url(
url = "https://api.twitter.com/oauth/access_token",
query = list(
oauth_verifier = verfier_code,
oauth_token = token
)
)
)
return(response)
}
authUrl <- get_authorization_url(app, callback = "oob")
after this, I get authorization link from authUrl[[1]] and visit the link from my browser. Authorize the app and copy the code. Then use the get_user_oauth_token() to get the token and secret as follows:
token <- get_user_oauth_token("THE_CODE_FROM_TWITTER", authURL[[2]])
token <- content(token, type = "application/x-www-form-urlencoded")
Now I want to use the user's oauth_token and secret to post a tweet. I am following this documentation.
response <- POST(
url = modify_url(
url = "https://api.twitter.com/1.1/statuses/update.json",
query = list(status = "Hello")
),
create_oauth_signature("https://api.twitter.com/1.1/statuses/update.json", "POST", app, token = token$oauth_token, token_secret = token$oauth_token_secret),
content_type("application/json")
)
But I am getting the following error:
$`{"errors":[{"code":32,"message":"Could not authenticate you."}]}`
I am sure that the credentials are valid. Because If I use the same credentials with rtweet::post_tweet() it works just fine.
It would be so helpful if anybody could just point out what I am doing wrong.
Thanks in advance.
I am trying to fetch all my mailinglists contacts using the following custom function, but contact lists didn't download all the records inside them. Idk what I am doing wrong?
get_all_contacts<-function(mailingListID){
directoryId<-"POOL_XXXXXXXXXX"
apiToken<-"XXXXXXXXXX"
fetch_url<- VERB(verb = "GET", url = paste("https://iad1.qualtrics.com/API/v3/directories/", directoryId,
"/mailinglists/",mailingListID ,"/contacts",sep = ""),
add_headers(`X-API-TOKEN` = apiToken), encode = "json")
fetch_url<-content(fetch_url, "parse",encoding = "UTF-8")
fetch_url<-fetch_url$result$nextPage
elements <- list()
while(!is.null(fetch_url)){
res<- VERB(verb = "GET", url = fetch_url,
add_headers(`X-API-TOKEN` = apiToken),
encode = "json")
res<-content(res, "parse",encoding = "UTF-8")
elements <- append(elements,res$result$elements)
fetch_url <- res$result$nextPage
}
return(elements)
}
How would one set up logging each request to a different json file with RestRserve?
I tried using the lgr package (referred to in RestRserve's doc on logging) like so:
library(RestRserve)
library(lgr)
app = Application$new(content_type = "text/plain")
# RestRserve logger
app$logger = RestRserve::Logger$new(level = "trace", name = "mylogger",
printer=function(timestamp, level, logger_name, pid, message, ...)
{
lgr$log(level=tolower(level), msg=message, ...)
}
)
# JSON appender in lgr
tf <- tempfile(tmpdir="D:/temp", fileext=".log")
lgr$add_appender(AppenderJson$new(tf), name = "json")
# Endpoint
app$add_get("/sqrt", function(request, response) {
on.exit({
# Next log file
tf <- tempfile(tmpdir="D:/temp", fileext=".log")
lgr$appenders$json$set_file(tf)
})
app$logger$info(msg="", context=list(request_id = request$id, message="Process start"))
response$body = sqrt(x)
app$logger$info(msg="", context=list(request_id = request$id, message="Process end"))
})
# Submit request
request = Request$new(path = "/sqrt", method = "GET", parameters_query = list(x = "10"))
response = app$process_request(request)
But this splits up a request's log info across two files. I'm also quite sure it wouldn't work for simultaneous requests.
I believe you even don't need any special logger - just use writeLines. Also you can rely on req$id to name files since it is unique.
library(RestRserve)
req = Request$new()
res = Response$new()
fl = file.path(tempdir(), paste0(req$id, ".log"))
con = file(fl, open = "at")
writeLines("Process start", con)
res$set_body(sqrt(10))
writeLines("Process end", con)
close(con)
readLines(fl)
unlink(fl)
A simple post using the httr package always ends with an error?
# Post a random meme and print its url
res <- httr::POST(
url = "https://api.imgflip.com/caption_image",
body = list(
template_id = "61579",
username = "<my-username>",
password = "<my-password>",
text0 = "abc",
text1 = "def",
font = "impact",
max_font_size = "50"
),
httr::verbose(),
encode = "json"
)
httr::content(res, "text")
Im not sure how to do it in R, but I tried using postman and sending the request as JSON do not work you have to send it as a form-data:
I'm trying to request some data via the mt gox API (mtgox.com) and theres some example code in python that I'd like to basically copy into R.
import hmac, base64, hashlib, urllib2
base = 'https://data.mtgox.com/api/2/'
def makereq(key, secret, path, data):
hash_data = path + chr(0) + data
secret = base64.b64decode(secret)
sha512 = hashlib.sha512
hmac = str(hmac.new(secret, hash_data, sha512))
header = {
'User-Agent': 'My-First-Trade-Bot',
'Rest-Key': key,
'Rest-Sign': base64.b64encode(hmac),
'Accept-encoding': 'GZIP',
}
return urllib2.Request(base + path, data, header)
I have some R code already
install.packages("base64")
install.packages("caTools")
install.packages("digest")
install.packages("RCurl")
library(RCurl)
library(caTools)
library(base64)
base<- "https://data.mtgox.com/api/2"
path<- "BTCUSD/money/ticker"
APIkey<-"******" #this is private but its a long hex number
secretAPIkey<-"*****" #this too, but this is in base64
makeReq<-function(key, secret, path, post_data)
{
browser()
message <- paste(path, NULL, post_data)
secret<-base64decode(secret,"character")
theHmac <-hmac(secret,message,"sha512")
header <-
{
c(
User.Agent = "My Bot",
Rest.Key = key,
Rest.Sign = base64encode(theHmac),
Acccept.encoding = "GZIP"
)
}
return (getURL(paste(base,path), post_data, header) )
}
I don't know how to get the "header" thing to work though, and I might be using getURL() incorrectly.
If you want to see the whole problem, the instructions are here https://bitbucket.org/nitrous/mtgox-api/overview, scroll down to the first block of code.
but I'm probably just making some elementary mistake with R header syntax...
try to use postForm (from RCurl) instead of getURL:
postForm(paste(base,path),
.opts = list(postfields = post_data,
useragent = 'R',
httpheader = c('Rest-Key' = key,
'Rest-Sign' = base64encode(theHmac)),
timeout = 4,
ssl.verifypeer = FALSE)
)