Learn R Programming

crul (version 0.1.6)

HttpClient: HTTP client

Description

HTTP client

Arguments

url
(character) A url. One of url or handle required.
opts
(list) curl options
handle
A handle

Details

Methods

Possible parameters (not all are allowed in each HTTP verb):

  • path - URL path, appended to the base URL
  • query - query terms, as a list
  • body - body as an R list
  • disk - a path to write to. if NULL (default), memory used
  • stream - an R function to determine how to stream data. if NULL (default), memory used
  • ... curl options, only those in the acceptable set from curl_options except the following: httpget, httppost, post, postfields, postfieldsize, and customrequest

Examples

Run this code
(x <- HttpClient$new(url = "https://httpbin.org"))
x$url
(res_get1 <- x$get('get'))
res_get1$content
res_get1$response_headers
res_get1$parse()

(res_get2 <- x$get('get', query = list(hello = "world")))
res_get2$parse()
library("jsonlite")
jsonlite::fromJSON(res_get2$parse())

# post request
(res_post <- x$post('post', body = list(hello = "world")))

## empty body request
x$post('post')

# put request
(res_put <- x$put('put'))

# delete request
(res_delete <- x$delete('delete'))

# patch request
(res_patch <- x$patch('patch'))

# head request
(res_head <- x$head())

# set curl options on client initialization
(res <- HttpClient$new(
  url = "https://httpbin.org",
  opts = list(
    verbose = TRUE,
    useragent = "hello world"
  )
))
res$opts
res$get('get')

# or set curl options when performing HTTP operation
(res <- HttpClient$new(url = "https://httpbin.org"))
res$get('get', verbose = TRUE)
## Not run: res$get('get', stuff = "things")
## Not run: res$get('get', httpget = TRUE)


# set headers
(res <- HttpClient$new(
  url = "https://httpbin.org",
  opts = list(
    verbose = TRUE
  ),
  headers = list(
    a = "stuff",
    b = "things"
  )
))
res$headers
# reassign header value
res$headers$a <- "that"
# define new header
res$headers$c <- "what"
# request
res$get('get')


# handles - pass in your own handle
h <- handle("https://httpbin.org")
(res <- HttpClient$new(handle = h))
out <- res$get("get")

# write to disk
(x <- HttpClient$new(url = "https://httpbin.org"))
f <- tempfile()
res <- x$get(disk = f)
res$content # when using write to disk, content is a path
readLines(res$content)

# streaming response
(x <- HttpClient$new(url = "https://httpbin.org"))
res <- x$get('stream/50', stream = function(x) cat(rawToChar(x)))
res$content # when streaming, content is NULL

Run the code above in your browser using DataLab