如何用Python写一个http post请求
1个回答
展开全部
python发送post和get请求
get请求:
使用get方式时,请求数据直接放在url中。
方法一、
import urllib
import urllib2
url = "<a href="http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"" target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"</a>
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
import httplib
url = "<a href="http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"" target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"</a>
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="GET",url=url)
response = conn.getresponse()
res= response.read()
print res
post请求:
使用post方式时,数据放在data或者body中,不能放在url中,放在url中将被忽略。
方法一、
import urllib
import urllib2
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "<a href="http://192.168.81.16/cgi-bin/python_test/test.py"" target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py"</a>
req = urllib2.Request(url = requrl,data =test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
import urllib
import httplib
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "<a href="http://192.168.81.16/cgi-bin/python_test/test.py"" target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py"</a>
headerdata = {"Host":"192.168.81.16"}
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata)
response = conn.getresponse()
res= response.read()
print res
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询