python通过get方式,post方式发送http请求和接收http响应-urllib urllib2

python发送post和get请求

get请求:

使用get方式时,请求数据直接放在url中。

import urllib
import urllib2

url="http://47.93.217.116:8003/short/token/"
req = urllib2.Request(url)
print req

res_data = urllib2.urlopen(req)
res = res_data.read()
print res

方法二、
import httplib

url="http://47.93.217.116:8003/short/token/"
conn = httplib.HTTPConnection("47.93.217.116")
conn.request(method="GET",url=url) 

response = conn.getresponse()
res= response.read()
print res

post请求:

使用post方式时,数据放在data或者body中,不能放在url中,放在url中将被忽略

import urllib
import urllib2
import json
test_data = {'user_id':'12'}
test_data_urlencode = urllib.urlencode(test_data)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
requrl = "http://47.93.217.116:8003/short/token/"
headers = {'User-Agent' : user_agent}
req = urllib2.Request(url = requrl,data =test_data_urlencode, headers=headers)
res_data = urllib2.urlopen(req)
res = res_data.read()
user_dict = json.loads(res)
print user_dict













猜你喜欢

转载自blog.csdn.net/kaikai136412162/article/details/80915998