背景
有些接口需要用post进行数据的传递。本文展示两种方式的POST请求。
方法1:
Request方式
代码
import urllib
import urllib2
import hashlib
import json
import time
strReq = "70635045"
urlnick = "http://myhello.cn/info_list"
servertime = int(time.time())
serverkey = "1233344444adasgahsgd"
serverid = "1218"
keytmp = serverid + serverkey + str(servertime)
key1 = hashlib.md5()
key1.update(keytmp)
key1 = key1.hexdigest()
jsonnick = "{\"id\":18,\"apid\":1802,\"source\":0,\"clientip\":\"1.1.10.57\",\"key\":\"" + key1
jsonnick = jsonnick + "\",\"servertime\":" + str(servertime) + ",\"t_userid_list\":"+strReq+"}"
req = urllib2.Request(url=urlnick, data=jsonnick)
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法2:
采用httplib方式
注意在域名上面的差别
import urllib
import urllib2
import hashlib
import json
import time
import httplib
strReq = "70635045"
urlnick = "myhello.cn"#注意这里的区别!!!
servertime = int(time.time())
serverkey = "1223344adsdssas"
serverid = "1218"
keytmp = serverid + serverkey + str(servertime)
key1 = hashlib.md5()
key1.update(keytmp)
key1 = key1.hexdigest()
jsonnick = "{\"id\":1218,\"apid\":1802,\"source\":0,\"clientip\":\"1.1.0.57\",\"key\":\"" + key1
jsonnick = jsonnick + "\",\"servertime\":" + str(servertime) + ",\"t_userid_list\":"+strReq+"}"
conn = httplib.HTTPConnection(urlnick)
conn.request("POST","/info_list",jsonnick)
response = conn.getresponse()
res = response.read()
print res