python requests发送post请求方式

2016年4月17日 发表评论 阅读评论

http的POST请求的编码有3种常用格式,具体如下:

application/x-www-form-urlencoded ==最常见的post提交数据的方式,以form表单形式提交数据
application/json    ==以json格式提交数据
multipart/form-data  ==一般使用来上传文件(较少用)

一、urlencoded 编码

这里使用httbin.org公共测试接口,代码如下:

#!/usr/bin/env python
# coding=utf8
# Copyright (C)  www.361way.com site All rights reserved.
import requests,json
url = 'http://httpbin.org/post'
data = {'key1':'value1','key2':'value2'}
r =requests.post(url,data)
print(r)
print(r.text)
print(r.content)

r.text返回的结果如下:

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "key1": "value1",
    "key2": "value2"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "23",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.18.4"
  },
  "json": null,
  "origin": "47.99.240.20, 47.99.240.20",
  "url": "https://httpbin.org/post"
}

这里post的结果其实相当于curl  'http://httpbin.org/post'  -d 'key1=value1&key2=value2' 。

二、post json请求

以json格式发送post请求代码如下:

import requests,json
url_json = 'http://httpbin.org/post'
data_json = json.dumps({'key1':'value1','key2':'value2'})   #dumps:将python对象解码为json数据
r_json = requests.post(url_json,data_json)
print(r_json)
print(r_json.text)
print(r_json.content)

r.text返回结果如下:

{
  "args": {},
  "data": "{\"key2\": \"value2\", \"key1\": \"value1\"}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "36",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.18.4"
  },
  "json": {
    "key1": "value1",
    "key2": "value2"
  },
  "origin": "47.99.240.20, 47.99.240.20",
  "url": "https://httpbin.org/post"
}

三、multipart请求

Requests以multipart形式发送post请求,具体代码实现如下所示:

import requests,json
url_mul = 'http://httpbin.org/post'
files = {'file':open('E://report.txt','rb')}
r = requests.post(url_mul,files=files)
print(r)
print(r.text)
print(r.content)

执行r.text结果如下:

{
  "args": {},
  "data": "",
  "files": {
    "file": "{'key1':'value1','key2':'value2'}\n"
  },
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "178",
    "Content-Type": "multipart/form-data; boundary=8462f97a62bb4d1fa863db2318196d28",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.18.4"
  },
  "json": null,
  "origin": "47.99.240.20, 47.99.240.20",
  "url": "https://httpbin.org/post"
}




本站的发展离不开您的资助,金额随意,欢迎来赏!

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.