python 发送请求

data = {"a":1,"b":2}

urllib2

get:

get_data = urllib.urlencode(data)
req_url = URL + '?' + get_data
req = urllib2.Request(url=req_url)
rsp = urllib2.urlopen(req).read()

post:

headers = {"Content-Type":"application/x-www-form-urlencode"}
#headers = {"Content-Type":"application/json"}
#headers = {"Content-Type":"application/form-data"}
一般来说我们使用的headers应该是json,或者正规一点也应该是form-data,但是由于我这里对接的系统使用的是request.getParameter(name)
来获取数据,这东西对给请求倒是一点问题没有,所以这里我们不得不用x-www-form-urlencode

req = urllib2.Request(url=URL, data=get_data, headers=headers)
rsp = urllib2.urlopen(req).read()


requests:

post:

  rsp = requests.post(URL, json=data, headers=headers)

或者 

  post_data = json.dumps(data, ensure_ascii=False) # 如果直接dumps出错,添加后面这个kwargs

  rsp = requests.post(URL, data=post_data, headers=headers)

原文地址:https://www.cnblogs.com/huaizhi/p/8524428.html