使用R语言elastic包连接Elasticsearch时遇请求头类型错误求助
Hey there, let's break down why you're seeing this error and how to fix it. The core issue here is that you're using use_proxy() incorrectly with the elastic package's connect() function.
What's Going Wrong?
The use_proxy() function from the curl package returns a configured curl handle object, not a set of HTTP headers. When you pass this object to the headers parameter of connect(), the function expects a simple list of string key-value pairs for HTTP headers (like list(Authorization = "Bearer token")), hence the error saying "All headers must be strings."
Correct Ways to Set Up Proxy for Elasticsearch Connection
Here are two straightforward methods to fix this:
Method 1: Pass Proxy Options Directly via curl_opts
You can specify proxy settings directly in the curl_opts parameter of connect(), which accepts a list of curl options:
library(elastic) library(curl) # Configure and connect with proxy elasticon <- connect( curl_opts = list( proxy = "http://xxx.xx.xx.xxx", proxyport = xxxx, proxyuserpwd = paste0("xxxxx@xxx.com:", "xxxxxxxx") ) )
- The
proxyuserpwdargument combines your username and password with a colon (:) — curl handles the authentication automatically with this format.
Method 2: Create a Pre-Configured Curl Handle
If you prefer more control, create a curl handle with proxy settings first, then pass it to connect():
library(elastic) library(curl) # Initialize a new curl handle proxy_handle <- new_handle() # Set proxy options on the handle handle_setopt(proxy_handle, proxy = "http://xxx.xx.xx.xxx", proxyport = xxxx, proxyuserpwd = "xxxxx@xxx.com:xxxxxxxx" ) # Connect using the pre-configured handle elasticon <- connect(handle = proxy_handle)
Quick Notes to Avoid Issues
- If your username or password contains special characters (like
@,!, or spaces), useURLencode()to escape them before combining intoproxyuserpwd. - Double-check that your proxy server allows incoming requests from your R environment, and that the proxy address/port are correct.
- Remember: The
headersparameter inconnect()is for HTTP request headers (like custom auth tokens or content types), not proxy configuration.
内容的提问来源于stack exchange,提问作者Mayank Lal

