Skip to content
Related Articles

Related Articles

Improve Article
Network Programming Python – HTTP Clients
  • Last Updated : 25 Oct, 2020

The request from the client in HTTP protocol reaches the server and fetches some data assuming it to be a valid request. This response from the server can be analyzed by using various methods provided by the requests module. Some of the ways below provide information about the response sent from the server to the Python program running on the client-side :

Getting initial Response

The get() method is used to get the basic information of the resources used at the server-side. This function fetches the data from the server and returns as a response object which can be printed in a simple text format.

Python3




# Import libraries
import requests
  
# Sending Request
req = requests.get('https://www.geeksforgeeks.org/')
  
# Show results
print(req.text[:2000])

Output:



Getting session-info

The session() method returns the session object which provides certain parameters to manipulate the requests. It can also manipulate cookies for all the requests initiated from the session object. If a large amount of requests are made to a single host then, the associated TCP connection is recalled.

Python3




# Import Libraries
import requests
  
# Creating Session
s = requests.Session()
  
# Getting Response
  
# Show Response
print(r.text)

Output:

{
  "cookies": {
    "sessioncookie": "419735271"
  }
}

Error Handling

If some error is raised in processing the request to the server, the exception is raised by the program which can be handled using the timeout attribute, which defines the time value until the program waits and after that, it raises the timeout error.

Python3




# Import Libraries
import requests
  
# Error Handling
try:
      
    # Creating Request
    req = requests.get('https://www.geeksforgeeks.org/', timeout=0.000001)
      
except requests.exceptions.RequestException as e:
      
    # Raising Error
    raise SystemExit(e)

Output:

HTTPSConnectionPool(host=’www.geeksforgeeks.org’, port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x0000018CFDAD83C8>, ‘Connection to www.geeksforgeeks.org timed out. (connect timeout=1e-06)’))

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :