Python中的简单URL GET/POST功能

TIM*_*MEX 74 python http

我似乎无法谷歌它,但我想要一个功能,这样做:

接受3个参数(或更多,无论如何):

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

返回结果和响应代码.

有没有这样做的代码片段?

bak*_*kal 105

要求

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
Run Code Online (Sandbox Code Playgroud)

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'}
Run Code Online (Sandbox Code Playgroud)

  • @ 3k不,他正在实例化`Http`类,而不是别名:`h = Http()`,而不是'h = Http`. (3认同)

rop*_*ble 52

更简单:通过请求模块.

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)
Run Code Online (Sandbox Code Playgroud)

要发送非表单编码的数据,请将其序列化为字符串(示例来自文档):

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)
Run Code Online (Sandbox Code Playgroud)

  • 在为我工作之前,我必须将post_data包装在json.dumps()中:`data = json.dumps(post_data)` (3认同)

Ian*_*bee 33

您可以使用它来包装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))
Run Code Online (Sandbox Code Playgroud)

这将返回一个包含结果数据和响应代码的Request对象.

  • 我更喜欢这个坚持标准库. (11认同)

Pau*_*ine 10

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'
                         )
Run Code Online (Sandbox Code Playgroud)

[更新]

其中一些答案很古老.今天我会使用requests像robaple这样的模块.


gre*_*pit 9

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

#!/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)
Run Code Online (Sandbox Code Playgroud)