Python中的简单URL GET/POST函数

Python中的简单URL GET/POST函数,python,http,Python,Http,我似乎不能用谷歌搜索它,但我想要一个能做到这一点的函数: 接受3个参数(或更多,无论什么): 网址 参数词典 投递或获取 将结果和响应代码返回给我 有这样的代码片段吗?请求 以下是一些常用的使用方法: import requests url = 'https://...' payload = {'key1': 'value1', 'key2': 'value2'} # GET r = requests.get(url) # GET with params in URL r = requ

我似乎不能用谷歌搜索它,但我想要一个能做到这一点的函数:

接受3个参数(或更多,无论什么):

  • 网址
  • 参数词典
  • 投递或获取
将结果和响应代码返回给我


有这样的代码片段吗?

请求

以下是一些常用的使用方法:

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


您可以使用它包装urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))
这将返回一个包含结果数据和响应代码的对象

import urllib

def fetch_thing(url, params, method):
    params = urllib.urlencode(params)
    if method=='POST':
        f = urllib.urlopen(url, params)
    else:
        f = urllib.urlopen(url+'?'+params)
    return (f.read(), f.code)


content, response_code = fetch_thing(
                              'http://google.com/', 
                              {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                              'GET'
                         )
[更新]

其中一些答案是古老的。今天,我会像robaple的回答一样使用
请求
模块。

更简单:通过模块

要发送未进行表单编码的数据,请将其序列化为字符串发送(示例取自):


我知道你要求GET和POST,但我会提供CRUD,因为其他人可能需要它以防万一:(这是在中测试的)


问题还不清楚——这是针对本地URL的,即,您正在编写服务器,或远程URL,即,您正在编写客户端?请在将来使用更多问题——描述性标题。我更喜欢这一个,因为它符合标准库。它应该是URL+“?”而不是URL+”&“?这很好,但准确地说,
Request
对象本身没有结果数据或响应代码-它需要通过类似于的方法进行“请求”。@Bach您这里有一个代码示例,它通过URLRequest方法实现了类似urlopen的“请求”部分吗?“我到处都找不到。”他们说,“杰姆,我已经引用过了。”。尝试
r=urlib2.urlopen(url)
,然后
r.readlines()
和/或
r.getcode()
。您可能还希望考虑使用它。我必须在JSON.DMSP()中包装PasyData(在我工作之前):<代码> DATS= JSON.DIPS(PASSYDATA)< /Cord> @ Matt,我认为这取决于您是否要提交表单编码数据(只传递一个DICT)或未编码的数据(在JSON数据串中传递)。我在这里查阅文档:这个模块是否有windows版本?@这个库(以及更多)是为windows编译的,在这里可以找到:你也可以使用httplib2中的
导入Http作为h
@3k不,他正在实例化
Http
类,而不是别名:
h=Http()
,你说得很对,我一定很累了。谢谢你的更正!如果您在没有第三方库的情况下以本机方式执行此操作,那就太好了。
import urllib

def fetch_thing(url, params, method):
    params = urllib.urlencode(params)
    if method=='POST':
        f = urllib.urlopen(url, params)
    else:
        f = urllib.urlopen(url+'?'+params)
    return (f.read(), f.code)


content, response_code = fetch_thing(
                              'http://google.com/', 
                              {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                              'GET'
                         )
import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)
import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)


print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)


print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)


print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)