发送post,没什么可说的
import urllib import urllib2 url = 'http://example.com/...' values = { 'productslug': 'bar','qty': 'bar' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = response.read() print result
发送 json 格式 post,不需要 urllib 进行 urlencode,但是需要 json.dumps(),同时需要发送头信息包含content-type
import urllib2 import json url = 'http://example.com/...' values = {"q":{"has_problems": "yes"}} data = json.dumps(values) req = urllib2.Request(url, data, {'Content-Type': 'application/json'}) response = urllib2.urlopen(req) result = response.read() print result
发送 json 格式 put 请求,只多加一行
import urllib2 import json url = 'http://example.com/...' values = {"q":{"has_problems": "yes"}} data = json.dumps(values) req = urllib2.Request(url, data, {'Content-Type': 'application/json'}) req.get_method = lambda:"PUT" response = urllib2.urlopen(req) result = response.read() print result
使用 httplib 发送 PUT 请求
update_data为 dict 类型 def postUpdate(update_data): path = "/api/posts/" + str(update_data['post_id']) params = json.dumps(update_data) conn = httplib.HTTPConnection("mypost.jpuyy.com", 80) conn.set_debuglevel(1) conn.request("PUT", path, params, headers) response = conn.getresponse() result = response.read() return result
Leave a Reply