python发送post和get请求

时间:2021-02-05 08:51:56

python发送post和get请求

get请求:

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

方法一、

import urllib
import urllib2 url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa" req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res

方法二、

import httplib

url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

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 = "http://192.168.81.16/cgi-bin/python_test/test.py" 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 = "http://192.168.81.16/cgi-bin/python_test/test.py"
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

对python中json的使用不清楚,所以临时使用了urllib.urlencode(test_data)方法