Python+requests implements interface testing-get and POST request use (Params__python

Source: Internet
Author: User

Original http://www.mamicode.com/info-detail-1755093.html




Introduction: Requests is written in Python language, based on Urllib, using APACHE2 licensed Open Source Protocol HTTP library. It is more convenient than urllib, can save us a lot of work, fully meet the requirements of HTTP testing. Requests's philosophy is centered on PEP's 20 idiom, so it's more pythoner than Urllib. The more important point is that it supports Python3 oh.

First, installation

To install the PIP:

PIP Install requests

After installation, run a simple example to see if the installation was successful:

Import requests                                 #导入requests包
r=requests.get (url= ' https://www.baidu.com/')    
print (R.status_code)                            #查看请求返回的状态
#结果
200

  

Two, several request type

①get Request: requests.get (' url ')

②post Request: Requests.post ("Url/post")

③put Request: Requests.put ("Url/put")

④delete Request: Requests.delete ("Url/delete")

⑤head Request: Requests.head ("Url/get")

⑥options Request: Requests.options ("Url/get")

Third, GET request

Passing URL parameters

In get requests, the params keyword is allowed to pass these parameters in a dictionary, for example:

content={' PageIndex ': 1, ' pageSize ': Ten, ' CategoryID ': 9}   
r=requests.get (' http://www.xxxxx.com/api/v2/ Activities ', params=content)
print (r.url)                       #获取请求内容
Print (r.text)                      #获取响应内容
#结果
http:// www.xxxx.com/api/v2/activities?pageIndex=1&pageSize=10&categoryId=9
{"Data": [], "PageIndex": 1, " Totalnum ": 0," Hasmore ": false," PageSize ": 0}

If the value of none exists in the dictionary, it is not added to the URL request.

content={' PageIndex ': 1, ' pageSize ': Ten, ' CategoryID ': None}   
r=requests.get (' http://www.xxxxx.com/api/v2/ Activities ', params=content)
print (r.url)                      

#结果
http://www.xxxx.com/api/v2/activities?pageIndex=1 &pagesize=10

  

PS: If you do not use params, you can also enter all the addresses in the request, the same effect, such as:

R=requests.get (' http://m.xxxxx.com/api/v2/activities?pageIndex=1&pageSize=10&categoryId=9 ')

Note: In some get requests, you need to identify the user, so you will need to send the cookie content in the request, such as some pages that require a user to log in to access, which will be explained in the following articles

Four, POST request

1. Pass parameters as form:

To send some form of data, simply pass a dictionary to the word, which is automatically encoded as a form when the request is sent, for example:

content={' key1 ': ' value1 ', ' key2 ': ' value2 '}
r=requests.post (' Http://www.xxx/api/v1/user/login ', data=content)

2. Passing parameters in JSON form:

In many cases, the data you want to send is not a form, but a JSON-formatted string, and if the content passed to the data keyword is not a dict, it is

A string, the data is sent directly when it is sent, and is not automatically encoded as form.

To convert a data structure to a JSON-formatted string, you first need to import a JSON package, two common methods: Json.dumps () and Json.loads ()

Import JSON
content={' name ': ' Nee ', ' age ': '
str_content=json.dumps ' (content)      #把dick编码为json格式的字符串
print (str_content)
print (Type (str_content))
#结果:
{"name": "Nee", "Age": "@"}
<class ' str ' >                        #此时的类型为str

content=json.loads (str_content)      #把json格式的字符串解码为原先的数据结构
Print (content)
Print (Type (content))
#结果
{' name ': ' Nee ', ' age ': ' <class '}
' Dict ' >

Note: The basic types of 1.json encoding support are: None, bool, int, float, string, list, tuple, Dict. For a dictionary, JSON assumes that the key is a string (any non-string key in the dictionary is converted to a string when encoded) and that the JSON specification should be encoded only for Python lists and dictionaries.                    In addition, in Web applications, it is a standard practice to define top-level objects as dictionaries. The 2.json encoded format is almost identical to the Python syntax, and slightly different: True will be mapped to True,false will be mapped to null and the tuple () will be mapped to list [], such as:

Content={' A ': None, ' B ': True, ' C ': False, ' d ':(1,2)}
str_content=json.dumps (content)
print (str_content)

#结果:
{"A": null, "B": True, "C": false, "D": [1, 2]}

so to use the Data keyword in a POST request to pass the JSON-formatted character channeling, you first have to convert Dict to string, for example:

Import Requests
import JSON
url= ' http://www.xxx.com/api/v1/user/login '
data={"ua": "13700002000", "PW" : "12QWASZX", "ct":
r=requests.post (Url,data=json.dumps (data))         #在一些post请求中, also need to use the headers section, not added here, The following will refer to   
print (r.text)

#结果
{"NewUser": false, "user": {"userId": 531, "Mobileno": "13700002000", "UserName ": Test User 2000" ...}

In addition to passing parameters as string, you can encode dick and pass it directly using the JSON keyword, which is encoded as a string when passed

Import requests            #不需要导入json模块
url= ' http://xxxx/api/v1/user/login '
data={"ua": "13700002000", "PW": " 12qwaszx ", CT":
r=requests.post (Url,json=data)

The head and cookie portions that are used in post requests. will be explained in the following articles

V. Response

1. Response status

After the request is sent successfully, you can use Status_code to view the corresponding status (the specific meaning of each state is not described in this article)

Import requests
R=requests.get (URL)
print (R.status_code)

-----Results-----
200

2. Response Content

In the above, the text has been shown to get the corresponding content, the returned content is string

Import requests
R=requests.get (URL)
print (R.text)
print (Type (r.text))       #查看返回内容的类型

----- The result-----                 ..... #返回的具体内容
<class ' str ' >              

In addition, requests has a built-in JSON decoder that converts the returned content to Dict

The Import requests
R.requests.get (URL) print (R.json ()) Print (
type (r.json))

-----Results-----
......
<class ' Dict ' >

Then after the JSON decoder to dict, it is more convenient to see the value of a specific parameter in the returned content.

3. Response Content Encoding format

When you get the response content, you can use r.encoding to view the encoding format of the content

Import requests
R=requests.get (URL)
print (r.encoding)

-----Results-----
UTF-8

You can also specify the encoding, and when the encoding is changed, the new encoding will be used each time the response is retrieved.

Import requests
R=requests.get (URL)
r.encoding= ' iso-8859-1 '
print (r.text)

4. Response header Content

Import requests
R=requests.get (URL)
print (r.headers)

5.cookies

Import requests
R=requests.get (URL)
print (r.cookies)


Python+reque

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.