国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python通過get,post方式發送http請求和接收http響應的方法

2020-02-23 01:26:38
字體:
來源:轉載
供稿:網友

本文實例講述了python通過get,post方式發送http請求和接收http響應的方法。分享給大家供大家參考。具體如下:

測試用CGI,名字為test.py,放在apache的cgi-bin目錄下:

#!/usr/bin/pythonimport cgidef main():   print "Content-type: text/html/n"  form = cgi.FieldStorage()  if form.has_key("ServiceCode") and form["ServiceCode"].value != "":    print "<h1> Hello",form["ServiceCode"].value,"</h1>"   else:      print "<h1> Error! Please enter first name.</h1>" main()

python發送post和get請求

get請求:

使用get方式時,請求數據直接放在url中。

方法一、

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

方法二、

import httpliburl = "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 urllibimport urllib2test_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 reqres_data = urllib2.urlopen(req)res = res_data.read()print res

方法二、

import urllibimport 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)方法;

模塊urllib,urllib2,httplib的區別

httplib實現了http和https的客戶端協議,但是在python中,模塊urllib和urllib2對httplib進行了更上層的封裝。

介紹下例子中用到的函數:

1、HTTPConnection函數

httplib.HTTPConnection(host[,port[,stict[,timeout]]])
這個是構造函數,表示一次與服務器之間的交互,即請求/響應
host 標識服務器主機(服務器IP或域名)
port 默認值是80
strict 模式是False,表示無法解析服務器返回的狀態行時,是否拋出BadStatusLine異常

例如:

conn = httplib.HTTPConnection("192.168.81.16",80) 與服務器建立鏈接。

2、HTTPConnection.request(method,url[,body[,header]])函數

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 万山特区| 时尚| 竹山县| 南京市| 东阳市| 宝丰县| 浑源县| 望江县| 云浮市| 彰武县| 商河县| 新宁县| 西充县| 长岭县| 石景山区| 和林格尔县| 武邑县| 额济纳旗| 墨竹工卡县| 鹿泉市| 富顺县| 罗源县| 舟曲县| 云霄县| 新兴县| 望谟县| 杭锦旗| 神农架林区| 九台市| 濮阳市| 当雄县| 彩票| 乃东县| 陆良县| 英德市| 会昌县| 龙井市| 繁峙县| 西安市| 建瓯市| 鹤山市|