Python使用Post和Get提交数据及数组传参示例

花开有时
花开有时
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍Python中通过Post和Get方式提交数据的方法,重点演示如何传递数组参数。包含无需Token的Post请求、携带Authorization Header的Post请求以及Get请求获取Token的代码示例,适用于需要处理JSON格式数据及身份验证的场景。

前言

近期在使用Python进行开发时,注意到网络上关于Post请求中如何传递数组作为参数的示例较少。基于实际项目经验,本文整理并分享相关实现代码,供读者参考学习。

具体示例如下:

首先展示基础的Post请求实现:

def http_post(): 
 url = "http://152.1.12.11:8080/web" 
 postdata = dict(d=2, p=10) 
 post = [] 
 post.append(postdata) 
 req = urllib2.Request(url, json.dumps(post)) #需要是json格式的参数 
 req.add_header('Content-Type', 'application/json') #要非常注意这行代码的写法 
 response = urllib2.urlopen(req) 
 result = json.loads(response.read()) 
 print result 

当接口需要身份验证Token时,Post请求的写法如下:

def http_post(): 
 url = "http://152.1.12.11:8080/web" 
 postdata = dict(d=2, p=10) 
 post = [] 
 post.append(postdata) 
 req = urllib2.Request(url, json.dumps(post)) 
 access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6I..........' 
 req.add_header('Authorization', access_token) #header中添加token 
 req.add_header('Content-Type', 'application/json') #要非常注意这行代码的写法 
 response = urllib2.urlopen(req) 
 result = json.loads(response.read()) 
 print result 

Get方式的请求实现如下:

def get_access_token(): 
 local_url = 'http://152.1.1.1:8080/web' 
 response = urllib2.urlopen(local_url).read() 
 resp = json.loads(response) 
 print resp 

总结

以上内容为本文的全部讲解,旨在帮助读者解决Python中数据提交的相关问题。若在使用过程中有任何疑问,欢迎留言讨论,感谢支持。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表