Customizing requests

To make use of the functionality that headers provide, we add headers to a request before sending it. To do this, we can't just use urlopen(). We need to follow these steps:

  • Create a Request object
  • Add headers to the request object
  • Use urlopen() to send the request object

We're going to learn how to customize a request for retrieving a Swedish version of the Debian home page. We will use the Accept-Language header, which tells the server our preferred language for the resource it returns. Note that not all servers hold versions of resources in multiple languages, so not all servers will respond to Accept-LanguageLinux home page.

First, we create a Request object:

>>> from urllib.request import Request
>>> req = Request('http://www.debian.org') ...

Get Learning Python Network Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.