📜  Python -HTTP请求

📅  最后修改于: 2020-11-06 06:26:59             🧑  作者: Mango


http或超文本传输协议适用于客户端服务器模型。通常,Web浏览器是客户端,托管网站的计算机是服务器。在Python,我们使用请求模块创建http请求。它是一个非常强大的模块,除了简单的请求和响应数据外,还可以处理http通信的许多方面。它可以处理身份验证,压缩/解压缩,分块请求等。

HTTP客户端以请求消息的形式向服务器发送HTTP请求,该消息包括以下格式:

  • 要求专线
  • 零个或多个标头(General | Request | Entity)字段,后跟CRLF
  • 空行(即CRLF之前没有任何内容的行)指示标头字段的结尾
  • 可选的消息正文

以下各节说明了HTTP请求消息中使用的每个实体。

请求线

请求行以方法令牌开头,然后是请求URI和协议版本,以CRLF结尾。元素由空格SP字符分隔。

Request-Line = Method SP Request-URI SP HTTP-Version CRLF

让我们讨论请求行中提到的每个部分。

申请方法

请求方法表示要对由给定Request-URI标识的资源执行的方法。该方法区分大小写,应始终以大写形式提及。下表列出了HTTP / 1.1中所有受支持的方法。

S.N. Method and Description
1 GET

The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.

2 HEAD

Same as GET, but it transfers the status line and the header section only.

3 POST

A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.

4 PUT

Replaces all the current representations of the target resource with the uploaded content.

5 DELETE

Removes all the current representations of the target resource given by URI.

6 CONNECT

Establishes a tunnel to the server identified by a given URI.

7 OPTIONS

Describe the communication options for the target resource.

8 TRACE

Performs a message loop back test along with the path to the target resource.

请求URI

Request-URI是统一资源标识符,用于标识在其上应用请求的资源。以下是最常用的形式来指定URI:

Request-URI = "*" | absoluteURI | abs_path | authority
S.N. Method and Description
1 The asterisk * is used when an HTTP request does not apply to a particular resource, but to the server itself, and is only allowed when the method used does not necessarily apply to a resource. For example:

OPTIONS * HTTP/1.1

2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is requested to forward the request or service from a valid cache, and return the response. For example:

GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1

3 The most common form of Request-URI is that used to identify a resource on an origin server or gateway. For example, a client wishing to retrieve a resource directly from the origin server would create a TCP connection to port 80 of the host “www.w3.org” and send the following lines:

GET /pub/WWW/TheProject.html HTTP/1.1

Host: www.w3.org

Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as “/” (the server root).

使用Python请求

我们将使用模块请求来了解http请求。

pip install requests 

在下面的示例中,我们看到了一个简单的GET请求并打印出响应结果的情况。我们选择仅打印前300个字符。

# How to make http request
import requests as req
r = req.get('http://www.tutorialspoint.com/python/')
print(r.text)[0:300]

当我们运行上面的程序时,我们得到以下输出-



     



Python Tutorial