python requests which port

Python Requests Which Port?

If you're working with Python requests library to make HTTP requests, it's important to understand how to specify the port number to use. By default, requests library uses port 80 for HTTP and port 443 for HTTPS. However, there may be scenarios where you need to use a different port number.

Specifying port number in URL

One way to specify a different port number is to include it in the URL. For example, if you want to make a request to a server running on port 8080, you can specify the URL as follows:

import requests

response = requests.get('')

Specifying port number in headers

Another way to specify a different port number is to set it in the headers of the request. You can do this by adding a Host header with the desired hostname and port number. For example:

import requests

headers = {
    'Host': ''

response = requests.get('', headers=headers)

Note that this method only works for HTTP requests.

Using a session object with custom adapter

If you need to make multiple requests with a custom port number, it may be more convenient to use a session object with a custom adapter. This allows you to reuse the same connection for multiple requests, which can improve performance.

import requests

session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100, max_retries=3, pool_block=True)
session.mount('http://', adapter)

response = session.get('')

In this example, we're creating a session object and a custom adapter with the desired port number. We're then mounting the adapter to the session object and using it to make the request.