python - Python 中的简单 URL GET/POST 函数

标签 python http

我似乎无法谷歌它,但我想要一个这样做的函数:

接受 3 个参数(或更多,随便):

  • 网址
  • 参数字典
  • POST 或 GET

将结果和响应代码返回给我。

有这样的片段吗?

最佳答案

请求

https://github.com/kennethreitz/requests/

以下是几种常用的使用方法:

import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}

# GET
r = requests.get(url)

# GET with params in URL
r = requests.get(url, params=payload)

# POST with form-encoded data
r = requests.post(url, data=payload)

# POST with JSON 
import json
r = requests.post(url, data=json.dumps(payload))

# Response, status etc
r.text
r.status_code

httplib2

https://github.com/jcgregorio/httplib2

>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
 'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT', 
 'content-type': 'text/html'}

关于python - Python 中的简单 URL GET/POST 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4476373/

相关文章:

http - 告诉网络浏览器登录失败,因此它不会要求记住密码

http - PUT 参数如何传递到页面?

http - Golang 反向代理以避免 SOP

python - 从循环中的函数返回两个值

python - Youtube GData观看次数最高为2000

python - 大范围连续整数的数据结构?

python - 尝试将 CSV 转换为数据帧时出现 IOError

javascript - Node JSON 输出格式错误,无法设置 HTTP header : Content-Length to fix

sockets - 传输一定数量的数据后 Chrome 挂起 - 等待可用的套接字

python-Twitter-api