Python发送Post请求及解析响应结果

一、Post请求

1、使用python发送一个Post请求

有时候遇到请求url中有很多参数。

1.1 示例1

accounts和pwd请到http://shop-xo.hctestedu.com/注册。

import requests

# 请求体
data = {
   
   
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 只有php项目需要application和application_client_type
# 写法一, 在请求Url中带上所有参数,application和application_client_type,用&隔开
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                                "s=api/user/login"
                                "&application=app"
                                "&applicaiton_client_type=weixin", json=data)

# 输出响应结果
print(response.text)

执行结果:

{"msg":"登录成功","code":0,"data":{"id":"7073","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"189","locking_integral":"0","referrer":"0","add_time":"1646195490","add_time_text":"2022-03-02 12:31:30","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxxx"}}

1.2 示例2

使用不定长参数 params,将url中需要的参数单独封装。

import requests

# 请求体
data = {
   
   
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 使用不定长参数params
param_data = {
   
   
    "application": "app",
    "application_client_type": "weixin"
}
# 写法2:使用不定长参数params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                             "s=api/user/login", params=param_data, json=data)

# 输出响应结果
print(response.text)

执行结果:

{"msg":"登录成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}

二、获取Response body

1、response.text

用type()查看response.text的类型,是str

import requests

# 请求体
data = {
   
   
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 使用不定长参数params
param_data = {
   
   
    "application": "app",
    "application_client_type": "weixin"
}
# 写法2:使用不定长参数params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                             "s=api/user/login", params=param_data, json=data)

# 输出响应结果
print(response.text)
print(type(response.text))

执行结果:

{"msg":"登录成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}
<class 'str'>

2、response.json()

用type()查看response.json()的类型,是dict

import requests

# 请求体
data = {
   
   
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 使用不定长参数params
param_data = {
   
   
    "application": "app",
    "application_client_type": "weixin"
}
# 写法2:使用不定长参数params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                             "s=api/user/login", params=param_data, json=data)

# 输出响应结果
print(response.json())
print(type(response.json()))

执行结果:

{"msg":"登录成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"
<think>好的,用户想学习如何使用Python发送POST请求并处理响应。我需要根据提供的引用内容来组织一个清晰的回答。首先,引用[1]提到了使用requests库发送POST请求,并包含数据和头部。引用[3]和[4]也提到了urllib和curl的例子,但用户可能更倾向于使用requests,因为它更简单。用户需要示例代码,所以应该提供一个基本的requests示例,同时考虑异常处理,如引用[4]提到的。此外,引用[2]提到User-Agent的重要性,可能需要包含设置请求头的部分。需要确保代码正确,并解释每个步骤。还要处理响应状态码、内容解析等。最后,生成相关问题,帮助用户深入学习。现在要检查是否有遗漏点,比如数据格式、headers设置、异常处理,以及如何解析JSON响应。确保回答结构清晰,分步骤说明,并符合用户的要求。</think>我将分步骤为您演示Python发送POST请求并处理响应的完整流程,结合代码示例进行说明: ### 一、基础POST请求实现 使用requests库发送POST请求的标准流程: ```python import requests # 目标URL url = 'https://httpbin.org/post' # 请求参数 payload = {'username': 'testuser', 'password': 'test123'} headers = {'User-Agent': 'Mozilla/5.0'} # 模拟浏览器访问[^2] try: # 发送POST请求 response = requests.post( url, data=payload, # 表单数据 headers=headers # 请求头设置 ) # 检查响应状态 if response.status_code == 200: print("请求成功!") print("响应内容:", response.text) # 原始文本响应 print("JSON格式:", response.json()) # 解析JSON响应 else: print(f"请求失败,状态码:{response.status_code}") except requests.exceptions.RequestException as e: print("请求异常:", str(e)) ``` ### 二、关键参数解析 1. **数据类型选择**: - `data`:发送表单数据(application/x-www-form-urlencoded) - `json`:发送JSON数据(application/json) ```python # 发送JSON数据 requests.post(url, json={'key': 'value'}) ``` 2. **文件上传**: ```python files = {'file': open('test.txt', 'rb')} requests.post(url, files=files) ``` 3. **超时设置**: ```python requests.post(url, timeout=5) # 5秒超时[^3] ``` ### 三、响应处理要点 1. **状态码判断**: ```python if response.ok: # 200-400范围内返回True # 处理成功响应 ``` 2. **内容解析方法**: ```python response.content # 二进制响应 response.text # UTF-8解码文本 response.json() # 尝试解析为JSON ``` 3. **获取响应头**: ```python response.headers['Content-Type'] ``` ### 四、完整请求流程示例 包含错误处理的完整实现: ```python import requests from requests.exceptions import HTTPError, Timeout def send_post_request(url, data): try: response = requests.post( url, json=data, headers={'Content-Type': 'application/json'}, timeout=10 ) response.raise_for_status() # 自动抛出4xx/5xx错误 return response.json() except Timeout: print("请求超时,请检查网络连接") except HTTPError as http_err: print(f"HTTP错误:{http_err}") except Exception as err: print(f"其他错误:{err}") # 使用示例 api_url = "https://api.example.com/login" response_data = send_post_request(api_url, {'user': 'admin'}) print(response_data) ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Summer@123

不积跬步无以至千里,感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值