How to Use a Proxy in R with httr and httr2: Step by Step

Published:

10 minute read

Acar Diveroli
Written by: Acar Diveroli
httr, httr2 and rvest blocks on a long shared base; only httr2 wears a blue req_proxy() band

In R, a proxy is a connection setting passed to libcurl, the library that sends the requests. You set it with req_proxy() in httr2, with use_proxy() in httr, or with environment variables. A setting passed through a function applies only to that request. An environment variable affects every libcurl request in the session. The trap is in rvest: read_html() opens the URL itself and never sees the req_proxy() setting. This post covers setup in both packages, environment variables, SOCKS5, reading pages with rvest and retries.

Setup with httr2

In httr2, the proxy is added to the request with the req_proxy() step. The signature is req_proxy(req, url, port = NULL, username = NULL, password = NULL, auth = "basic"). The function writes these values to libcurl's proxy, proxyport, proxyuserpwd and proxyauth options.

r
library(httr2)

resp <- request("https://httpbin.org/ip") |>
  req_proxy(
    "pr.proxynet.io",
    port = 8000,
    username = "user",
    password = "pass"
  ) |>
  req_perform()

# The "origin" field in the response is the proxy's exit IP
resp_body_json(resp)

The proxy address needs no scheme, even when the target is HTTPS. libcurl treats an address without a scheme as an HTTP proxy. It asks the proxy for a CONNECT tunnel and sets up TLS inside that tunnel.

Keep credentials out of the script. Read them as username = Sys.getenv("PROXY_USER") and password = Sys.getenv("PROXY_PASS"). You can store the values in the .Renviron file described below.

The auth argument accepts basic, digest, digest_ie, gssnegotiate, ntlm and any. For proxies that use a username and password, the default basic is enough.

One detail can break the password. libcurl URL-decodes the username and password in proxyuserpwd before using them. If the password contains %, write it as %25. A : in the username needs %3A.

Build the request object once and keep it in a variable. Every request derived from that object carries the same proxy setting.

Setup with httr

In httr, the proxy is a config object passed to the request function. The signature is use_proxy(url, port = NULL, username = NULL, password = NULL, auth = "basic"). The function produces the same libcurl options and goes into verbs such as GET() and POST() as an argument.

r
library(httr)

resp <- GET(
  "https://httpbin.org/ip",
  use_proxy(
    "pr.proxynet.io",
    port = 8000,
    username = "user",
    password = "pass"
  ),
  timeout(20)
)

content(resp)

To set it once for all requests, write set_config(use_proxy(...)). reset_config() removes it. To cover a single block of code, use with_config().

The httr page marks the package as "superseded". It only gets the changes needed to stay on CRAN, and its developers recommend httr2. Start new code with httr2. If you need to add a proxy to an old script without breaking it, use_proxy() is enough.

Environment variables

When no proxy is passed through a function, libcurl looks at environment variables. So once a variable is set, httr, httr2 and other libcurl-based packages all pick up the same proxy. A proxy passed through a function takes precedence over the environment variable.

VariableRequests it coversNote
http_proxyhttp:// targetsRead in lowercase only
https_proxyhttps:// targetsUppercase HTTPS_PROXY is read too
all_proxyAll, if the others are unsetScheme-specific variable wins
no_proxyAddresses that skip the proxyComma-separated host list

The first row causes frequent errors. If you write HTTP_PROXY and send a request to an http:// address, libcurl does not see the variable and the request goes out directly.

Set the variable for the open R session only with Sys.setenv():

r
Sys.setenv(
  https_proxy = "http://user:pass@pr.proxynet.io:8000",
  http_proxy  = "http://user:pass@pr.proxynet.io:8000",
  no_proxy    = "localhost,127.0.0.1"
)

For a permanent setting, write the same lines to the .Renviron file in your home directory, as https_proxy=http://.... R reads this file at startup. Restart the session after a change.

In an environment variable, the proxy is written as a single URL. Characters such as @ and # in the password split the address in this form. The password pass@123 is written as pass%40123. The encoding rules are in our post How to Read a Proxy URL.

An environment variable applies to every libcurl request in the session. Package downloads and calls from other libraries may be routed through this proxy too. If you want the proxy to apply only to specific requests, use req_proxy().

SOCKS5 and DNS

libcurl speaks SOCKS5 based on the scheme at the start of the proxy address. With socks5://, the target name is resolved on your machine. With socks5h://, the name is resolved on the proxy side. If you want the target resolved from the proxy's country, choose socks5h://.

r
resp <- request("https://httpbin.org/ip") |>
  req_proxy(
    "socks5h://pr.proxynet.io",
    port = 8000,
    username = Sys.getenv("PROXY_USER"),
    password = Sys.getenv("PROXY_PASS")
  ) |>
  req_perform()

In an environment variable, the same setting is all_proxy=socks5h://user:pass@pr.proxynet.io:8000. We covered the difference between the two schemes in detail in SOCKS5 vs SOCKS5H.

These R packages open TCP connections over SOCKS5. The Proxynet SOCKS5 Proxy also carries UDP, but httr and httr2 requests do not use it.

Reading pages with rvest

rvest's read_html() opens the URL itself. The function relies on the xml2 package and reads the URL through a curl::curl() connection. That connection knows nothing about the req_proxy() setting; it only sees environment variables. If there is no environment variable either, the page comes from your own IP and no warning appears.

The reliable path is to fetch the page with httr2 first and then hand it to rvest. resp_body_html() turns the response into an xml2 document. rvest functions work with that document directly.

r
library(httr2)
library(rvest)

resp <- request("https://example.com/") |>
  req_proxy(
    "pr.proxynet.io",
    port = 8000,
    username = Sys.getenv("PROXY_USER"),
    password = Sys.getenv("PROXY_PASS")
  ) |>
  req_throttle(capacity = 30, fill_time_s = 60) |>
  req_perform()

page <- resp_body_html(resp)
html_elements(page, "h1") |> html_text2()

If you use httr, you can write read_html(resp). xml2 includes a separate read method for the httr response object and takes the body from the response.

req_throttle(capacity = 30, fill_time_s = 60) sends at most 30 requests per minute. Check the site's terms and its robots.txt file before collecting pages. If there is an official API, use it.

Timeouts and retries

In httr2, req_timeout(seconds) sets an upper limit for the whole request. When the time runs out, the request fails. The function fills libcurl's timeout_ms option and resets the separate connect timeout. For requests through a proxy, a 20-30 second limit is a reasonable start.

req_retry() retries a failed request inside req_perform(). By default, only 429 and 503 responses count as transient. retry_on_failure = TRUE also makes libcurl errors, such as a dropped connection, retryable. With a proxy, this line matters.

r
req <- request("https://httpbin.org/ip") |>
  req_proxy("pr.proxynet.io", port = 8000,
            username = Sys.getenv("PROXY_USER"),
            password = Sys.getenv("PROXY_PASS")) |>
  req_timeout(30) |>
  req_retry(
    max_tries = 4,
    retry_on_failure = TRUE,
    is_transient = \(resp) resp_status(resp) %in% c(429, 502, 503)
  )

resp <- req_perform(req)

httr2 computes the wait time itself. If the response has a Retry-After header, it waits as long as the header says. Otherwise it applies a wait that grows with each attempt, is randomly spread and is capped at 60 seconds. The \(resp) shorthand function syntax works in R 4.1 and later.

The httr equivalent is RETRY(). With the default times = 3, it retries as long as http_error() returns true. That means it also repeats permanent errors such as 407. Exclude the permanent codes with terminate_on:

r
resp <- RETRY(
  "GET", "https://httpbin.org/ip",
  use_proxy("pr.proxynet.io", port = 8000,
            username = "user", password = "pass"),
  timeout(30),
  times = 4,
  terminate_on = c(401, 403, 404, 407)
)

Debugging

Most proxy problems show up in libcurl's error message. httr2 shows this message under the Failed to perform HTTP request error. For detail, add req_verbose(info = TRUE) to the request. In httr, verbose() does the same job. The output may show credentials, so check it before sharing.

SymptomLikely causeFix
IP echo shows your own IPread_html() opened the URL directly, or HTTP_PROXY was written in uppercaseFetch the page with httr2, use lowercase http_proxy
CONNECT tunnel failed, response 407Wrong username or passwordCheck the values and the % encoding
Could not resolve proxyProxy host name misspelledCheck the spelling of pr.proxynet.io
Timeout was reachedTime ran out or wrong portCheck the port and the req_timeout() value

We collected the proxy-side causes of the 407 error in How to Fix HTTP 407 Proxy Authentication Required. If the error appears only for HTTPS targets, the problem is most likely in the CONNECT tunnel.

To send a single request without the proxy, write req_options(proxy = ""). libcurl reads an empty proxy value as "use no proxy" and ignores the environment variable. This way you can tell whether the problem is in the proxy or the target site.

The bottom line

In new code, use httr2 and req_proxy(), read credentials from the .Renviron file, and add req_timeout() with req_retry(retry_on_failure = TRUE). Above all, do not pass a URL to rvest's read_html(). Fetch the page with httr2, or the proxy is silently bypassed. For jobs that need a country-specific exit IP, see the Residential Proxy page.

Sources

Frequently asked questions

How do I apply a proxy setting to the whole R session?

With an environment variable. When you write Sys.setenv(https_proxy = "http://user:pass@pr.proxynet.io:8000"), libcurl requests in the session use this proxy. For http:// targets, also set a lowercase http_proxy. To load the setting at every startup, put the same lines in the .Renviron file and restart the R session. To keep a single request out of this setting, use req_options(proxy = "").

Should I use httr or httr2?

httr2. httr's own page marks the package as "superseded" and recommends httr2 for new code. Both packages set up the proxy with the same libcurl options, so proxy behavior is the same. In httr2, retries, rate limits and timeouts are steps added to the request object. In old httr scripts, use_proxy() keeps working.

Why doesn't rvest read_html use the proxy?

Because read_html() opens the URL with its own connection. That connection does not see the req_proxy() setting in httr2; it only reads environment variables. Fetch the page through the proxy with req_perform() first, then pass it to rvest with resp_body_html(). If you use httr, you can pass the httr response object to read_html() instead of a URL. Either way, the page comes through the proxy.

How do I write special characters in a proxy password?

It depends on where you write it. In an environment variable, the proxy is a URL, so @, #, : and / are percent-encoded: the password pass@123 becomes pass%40123. In req_proxy() and use_proxy() arguments, @ stays as it is. libcurl URL-decodes these values, so there you only need to write % as %25.

Does a SOCKS5 proxy work in R?

Yes. httr and httr2 use libcurl, so putting socks5:// or socks5h:// in front of the proxy address is enough. socks5h:// resolves the target name on the proxy side, socks5:// on your machine. If you want country-specific results, choose socks5h://. In an environment variable, the same address can be set with all_proxy. The username and password go in the username and password arguments, as with an HTTP proxy.

How do I check that the proxy is working?

Send a request to an IP echo service. A request built with request("https://httpbin.org/ip") returns the address the server sees in the response's origin field. If this address differs from your public IP, the request went out through the proxy. If it is the same, check that the req_proxy() step is in the request and check the case of the environment variable. For detail, add req_verbose(info = TRUE) to the request.

Ask ChatGPTAsk Claude