HTTP? httr! (1)
Downloading a file from the Internet means sending a GET request and receiving the file you asked for. Internally, all the previously discussed functions use a GET request to download files.
httr
provides a convenient function, GET()
to execute this GET request. The result is a response
object, that provides easy access to the status code, content-type and, of course, the actual content.
You can extract the content from the request using the content()
function. At the time of writing, there are three ways to retrieve this content: as a raw object, as a character vector, or an R object, such as a list. If you don't tell content()
how to retrieve the content through the as
argument, it'll try its best to figure out which type is most appropriate based on the content-type.
This exercise is part of the course
Intermediate Importing Data in R
Exercise instructions
- Load the
httr
package. It's already installed on DataCamp's servers. - Use
GET()
to get the URL stored inurl
. Store the result of thisGET()
call asresp
. - Print the
resp
object. What information does it contain? - Get the content of
resp
usingcontent()
and set theas
argument to"raw"
. Assign the resulting vector toraw_content
. - Print the first values in
raw_content
withhead()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Load the httr package
# Get the url, save response to resp
url <- "http://www.example.com/"
# Print resp
# Get the raw content of resp: raw_content
# Print the head of raw_content