the points are not contradicting, creating a new instance of CloseableHttpClient
is expensive, but it is also fully thread-safe, so multiple threads can use the same instance of CloseableHttpClient
to execute multiple requests concurrently.
To change credentials for different requests that use the same client, you can use the CredentialsProvider
class to manage your credentials.
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.CredentialsProvider
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
# Create a credentials provider and set the credentials for a specific AuthScope
creds_provider = BasicCredentialsProvider()
creds_provider.set_credentials(AuthScope("localhost", 8080), UsernamePasswordCredentials("user1", "password1"))
# Create an HttpClientBuilder and set the credentials provider
http_client_builder = HttpClients.custom().setDefaultCredentialsProvider(creds_provider)
# Build the CloseableHttpClient instance
http_client = http_client_builder.build()
# Use the CloseableHttpClient instance to execute your requests
response1 = http_client.execute(request1)
response2 = http_client.execute(request2)
# Set different credentials for a different AuthScope
creds_provider.set_credentials(AuthScope("localhost", 8081), UsernamePasswordCredentials("user2", "password2"))
# Use the same CloseableHttpClient instance to execute another request with different credentials
response3 = http_client.execute(request3)