..

python 使用 urllib2 发送 PUT 请求

默认是没法直接设置请求方法为 PUT 的,需要重写请求对象得 get_method 方法,让这个方法返回 PUT

import urllib2

def put_request(url, data):
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = urllib2.Request(url, data=data)
    request.get_method = lambda: 'PUT'
    response = opener.open(request)
    return response.read()

# 示例用法
url = 'http://example.com/api'
data = '{"key": "value"}'
result = put_request(url, data)
print(result)