Python使用post及get方式提交数据的实例

yipeiwu_com5年前Python基础

最近在使用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时写法如下:

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设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

如何在Cloud Studio上执行Python代码?

如何在Cloud Studio上执行Python代码?

1.在python文件下新建python文件,输入文件名后按Enter键生成,比如: one.py . 2.简单输入python代码: print "haha" 3.打开左下角的终端...

详解MySQL数据类型int(M)中M的含义

介绍 MySQL 数据类型中的 integer types 有点奇怪。你可能会见到诸如:int(3)、int(4)、int(8) 之类的 int 数据类型。刚接触 MySQL 的时候,我...

详解Python中内置的NotImplemented类型的用法

它是什么?   >>> type(NotImplemented) <type 'NotImplementedType'> NotImpl...

Python+pyplot绘制带文本标注的柱状图方法

Python+pyplot绘制带文本标注的柱状图方法

如下所示: import numpy as np import matplotlib.pyplot as plt # 生成测试数据 x = np.linspace(0, 10,...

python将文本中的空格替换为换行的方法

python将文本中的空格替换为换行的方法

测试文本 jb51.txt welcome to jb51.net I love you very much python代码 # -*- coding: utf-8 -*- '...