
- Python - Network Programming
- Python - Network Introduction
- Python - Network Environment
- Python - Internet Protocol
- Python - IP Address
- Python - DNS Lookup
- Python - Routing
- Python - HTTP Requests
- Python - HTTP Response
- Python - HTTP Headers
- Python - Custom HTTP Requests
- Python - Request Status Codes
- Python - HTTP Authentication
- Python - HTTP Data Download
- Python - Connection Re-use
- Python - Network Interface
- Python - Sockets Programming
- Python - HTTP Client
- Python - HTTP Server
- Python - Building URLs
- Python - WebForm Submission
- Python - Databases and SQL
- Python - Telnet
- Python - Email Messages
- Python - SMTP
- Python - POP3
- Python - IMAP
- Python - SSH
- Python - FTP
- Python - SFTP
- Python - Web Servers
- Python - Uploading Data
- Python - Proxy Server
- Python - Directory Listing
- Python - Remote Procedure Call
- Python - RPC JSON Server
- Python - Google Maps
- Python - RSS Feed
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - HTTP Client
In the http protocol, the request from the client reaches the server and fetches some data and metadata assuming it is a valid request. We can analyze this response from the server using various functions available in the python requests module. Here the below python programs run in the client side and display the result of the response sent by the server.
Get Initial Response
In the below program the get method from requests module fetches the data from a server and it is printed in plain text format.
import requests r = requests.get('https://httpbin.org/') print(r.text)[:200]
When we run the above program, we get the following output −
<!DOCTYPE html > <html lang="en"> <head> <meta charset="UTF-8"> <title>httpbin.org</title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+
Get Session Object Response
The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance. If you’re making several requests to the same host, the underlying TCP connection will be reused.
import requests s = requests.Session() s.get('http://httpbin.org/cookies/set/sessioncookie/31251425') r = s.get('http://httpbin.org/cookies') print(r.text)
When we run the above program, we get the following output −
{"cookies":{"sessioncookie":"31251425"}}
Handling Error
In case some error is raised because of issue in processing the request by the server, the python program can gracefully handle the exception raised using the timeout parameter as shown below. The program will wait for the defined value of the timeout error and then raise the time out error.
requests.get('http://github.com', timeout=10.001)