import requests
def make_request_with_timeout(url, timeout):
"""
Makes an HTTP request to the given URL with a timeout.
Args:
url (str): The URL to request.
timeout (int): The timeout in seconds.
Returns:
requests.Response: The response object if the request is successful,
or None if an error occurs.
"""
try:
response = requests.get(url, timeout=timeout) # Send the request with timeout
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response
except requests.exceptions.RequestException as e:
print(f"Error making request to {url}: {e}") # Print the error message
return None
if __name__ == '__main__':
# Example usage
url = "https://www.example.com"
timeout = 5
response = make_request_with_timeout(url, timeout)
if response:
print("Request successful!")
# Process the response
print(response.status_code)
else:
print("Request failed.")
Add your comment