導航:首頁 > 編程語言 > httpheaderpython

httpheaderpython

發布時間:2022-04-25 05:49:38

A. python http referer欄位怎麼用

HTTP Referer是header的一部分,當瀏覽器向web伺服器發送請求的時候,一般會帶上Referer,告訴伺服器我是從哪個頁面鏈接過來的,伺服器籍此可以獲得一些信息用於處理。用於統計訪問量、防外連接等。

B. python 可以偽造 ip 發送 http 請求嗎

有些 web 伺服器校驗客戶端的真實 ip 是直接從 http headers 里邊讀,可以偽造 x-forward-for, x-real-ip 來欺騙 web 伺服器,但是大部分都沒辦法通過這種辦法來偽造。

C. python的httplib,urllib和urllib2的區別及用

宗述
首先來看一下他們的區別
urllib和urllib2
urllib 和urllib2都是接受URL請求的相關模塊,但是urllib2可以接受一個Request類的實例來設置URL請求的headers,urllib僅可以接受URL。
這意味著,你不可以偽裝你的User Agent字元串等。
urllib提供urlencode方法用來GET查詢字元串的產生,而urllib2沒有。這是為何urllib常和urllib2一起使用的原因。
目前的大部分http請求都是通過urllib2來訪問的

httplib
httplib實現了HTTP和HTTPS的客戶端協議,一般不直接使用,在更高層的封裝模塊中(urllib,urllib2)使用了它的http實現。

urllib簡單用法
urllib.urlopen(url[, data[, proxies]]) :
[python] view plain

google = urllib.urlopen('')
print 'http header:/n', google.info()
print 'http status:', google.getcode()
print 'url:', google.geturl()
for line in google: # 就像在操作本地文件
print line,
google.close()

詳細使用方法見
urllib學習

urllib2簡單用法
最簡單的形式
import urllib2
response=urllib2.urlopen(')
html=response.read()

實際步驟:
1、urllib2.Request()的功能是構造一個請求信息,返回的req就是一個構造好的請求
2、urllib2.urlopen()的功能是發送剛剛構造好的請求req,並返回一個文件類的對象response,包括了所有的返回信息。
3、通過response.read()可以讀取到response裡面的html,通過response.info()可以讀到一些額外的信息。
如下:

#!/usr/bin/env python
import urllib2
req = urllib2.Request("")
response = urllib2.urlopen(req)
html = response.read()
print html

有時你會碰到,程序也對,但是伺服器拒絕你的訪問。這是為什麼呢?問題出在請求中的頭信息(header)。 有的服務端有潔癖,不喜歡程序來觸摸它。這個時候你需要將你的程序偽裝成瀏覽器來發出請求。請求的方式就包含在header中。
常見的情形:

import urllib
import urllib2
url = '
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'# 將user_agent寫入頭信息
values = {'name' : 'who','password':'123456'}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

values是post數據
GET方法
例如網路:
,這樣我們需要將{『wd』:』xxx』}這個字典進行urlencode

#coding:utf-8
import urllib
import urllib2
url = ''
values = {'wd':'D_in'}
data = urllib.urlencode(values)
print data
url2 = url+'?'+data
response = urllib2.urlopen(url2)
the_page = response.read()
print the_page

POST方法

import urllib
import urllib2
url = ''
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' //將user_agent寫入頭信息
values = {'name' : 'who','password':'123456'} //post數據
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values) //對post數據進行url編碼
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

urllib2帶cookie的使用

#coding:utf-8
import urllib2,urllib
import cookielib

url = r''

#創建一個cj的cookie的容器
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#將要POST出去的數據進行編碼
data = urllib.urlencode({"email":email,"password":pass})
r = opener.open(url,data)
print cj

httplib簡單用法
簡單示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import httplib
import urllib

def sendhttp():
data = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection('bugs.python.org')
conn.request('POST', '/', data, headers)
httpres = conn.getresponse()
print httpres.status
print httpres.reason
print httpres.read()

if __name__ == '__main__':
sendhttp()

具體用法見
httplib模塊
python 3.x中urllib庫和urilib2庫合並成了urllib庫。其中、
首先你導入模塊由
import urllib
import urllib2
變成了
import urllib.request

然後是urllib2中的方法使用變成了如下
urllib2.urlopen()變成了urllib.request.urlopen()
urllib2.Request()變成了urllib.request.Request()

urllib2.URLError 變成了urllib.error.URLError
而當你想使用urllib 帶數據的post請求時,
在python2中
urllib.urlencode(data)

而在python3中就變成了
urllib.parse.urlencode(data)

腳本使用舉例:
python 2中

import urllib
import urllib2
import json
from config import settings
def url_request(self, action, url, **extra_data): abs_url = "http://%s:%s/%s" % (settings.configs['Server'],
settings.configs["ServerPort"],
url)
if action in ('get', 'GET'):
print(abs_url, extra_data)
try:
req = urllib2.Request(abs_url)
req_data = urllib2.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
# print "-->server response:",callback
return callback

except urllib2.URLError as e:
exit("\033[31;1m%s\033[0m" % e)
elif action in ('post', 'POST'):
# print(abs_url,extra_data['params'])
try:
data_encode = urllib.urlencode(extra_data['params'])
req = urllib2.Request(url=abs_url, data=data_encode)
res_data = urllib2.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = res_data.read()
callback = json.loads(callback)
print("\033[31;1m[%s]:[%s]\033[0m response:\n%s" % (action, abs_url, callback))
return callback
except Exception as e:
print('---exec', e)
exit("\033[31;1m%s\033[0m" % e)

python3.x中

import urllib.request
import json
from config import settings

def url_request(self, action, url, **extra_data):
abs_url = 'http://%s:%s/%s/' % (settings.configs['ServerIp'], settings.configs['ServerPort'], url)
if action in ('get', 'Get'): # get請求
print(action, extra_data)try:
req = urllib.request.Request(abs_url)
req_data = urllib.request.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
return callback
except urllib.error.URLError as e:
exit("\033[31;1m%s\033[0m" % e)
elif action in ('post', 'POST'): # post數據到伺服器端
try:
data_encode = urllib.parse.urlencode(extra_data['params'])
req = urllib.request.Request(url=abs_url, data=data_encode)
req_data = urllib.request.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
callback = json.loads(callback.decode())
return callback
except urllib.request.URLError as e:
print('---exec', e)
exit("\033[31;1m%s\033[0m" % e)

settings配置如下:

configs = {
'HostID': 2,
"Server": "localhost",
"ServerPort": 8000,
"urls": {

'get_configs': ['api/client/config', 'get'], #acquire all the services will be monitored
'service_report': ['api/client/service/report/', 'post'],

},
'RequestTimeout': 30,
'ConfigUpdateInterval': 300, # 5 mins as default

}

D. 使用python的requests庫運行http請求,請問如圖的報錯是什麼原因,要怎麼解決的

post的參數順序再檢查確認一下,可以使用類似data=data,header=head的方式賦值避免混淆。

E. python3.6.1 的請求頭里的橫杠前後自動大寫怎麼辦

http header fields 是 case insensitive 的,所以 Python 把你的 header 變成任何大小寫都是正確的,並且你也不應該依賴於 header field 的大小寫。
標准沒有說過哪種形式更好,不過 common sense 是橫杠間隔的大寫開頭單詞。

F. 怎麼知道python發送了什麼http請求

本文實例講述了python通過get,post方式發送http請求和接收http響應的方法。分享給大家供大家參考。具體如下:
測試用CGI,名字為test.py,放在apache的cgi-bin目錄下:
#!/usr/bin/python
import cgi
def 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 urllib
import urllib2
url = "test.py?ServiceCode=aaaa"
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res

方法二、
import httplib
url = "hest/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 = "/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 = "python_test/test.py"
headerdata = {"Host":"116"}
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("1.16",80) 與伺服器建立鏈接。
2、HTTPConnection.request(method,url[,body[,header]])函數
這個是向伺服器發送請求
method 請求的方式,一般是post或者get,
例如:
method="POST"或method="Get"
url 請求的資源,請求的資源(頁面或者CGI,我們這里是CGI)
例如:
url="htti-bin/python_test/test.py" 請求CGI
或者
url="ht_test/test.html" 請求頁面
body 需要提交到伺服器的數據,可以用json,也可以用上面的格式,json需要調用json模塊
headers 請求的http頭headerdata = {"Host":"192.168.81.16"}
例如:
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "hgi-bin/python_test/test.py"
headerdata = {"Host":"192.116"}
conn = httplib.HTTPConnection("196",80)
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata)

conn在使用完畢後,應該關閉,conn.close()
3、HTTPConnection.getresponse()函數
這個是獲取http響應,返回的對象是HTTPResponse的實例。
4、HTTPResponse介紹:
HTTPResponse的屬性如下:
read([amt]) 獲取響應消息體,amt表示從響應流中讀取指定位元組的數據,沒有指定時,將全部數據讀出;
getheader(name[,default]) 獲得響應的header,name是表示頭域名,在沒有頭域名的時候,default用來指定返回值
getheaders() 以列表的形式獲得header
例如:
date=response.getheader('date');
print date
resheader=''
resheader=response.getheaders();
print resheader

列形式的響應頭部信息:
[('content-length', '295'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 31 Mar 2012 10:07:02 GMT'), ('connection', 'close'), ('etag', '"e8744-127-4bc871e4fdd80"'), ('date', 'Mon, 03 Sep 2012 10:01:47 GMT'), ('content-type', 'text/html')]
date=response.getheader('date');
print date

取出響應頭部的date的值。

G. 一下python代碼中的headers是什麼意思,怎麼理解

headers參數指定HTTP請求附件頭部信息,有時候附件的頭信息確實沒有影響,因為伺服器為了增加包容性,會盡可能使得更加廣泛的情形都正常工作。

H. python爬蟲 如何解決http error 503問題

從表面上看,Python爬蟲程序運行中出現503錯誤是伺服器的問題,其實真正的原因在程序,由於Python腳本運行過程中讀取的速度太快,明顯是自動讀取而不是人工查詢讀取,這時伺服器為了節省資源就會給Python腳本反饋回503錯誤。其實只要把爬取的速度放慢一點就好了。比如讀取一條記錄或幾條記錄後適當添加上time.sleep(10),這樣就基本上不會出現503錯誤了。我本人在使用中一般是在每一次讀取後都運行time.sleep(1)或time.sleep(3),具體的數值根據不同的網站確定。

I. 如何用Python寫一個http post請求

HTTP 協議規定 POST 提交的數據必須放在消息主體(entity-body)中,但協議並沒有規定數據必須使用什麼編碼方式。常見的四種編碼方式如下:
1、application/x-www-form-urlencoded
這應該是最常見的 POST 提交數據的方式了。瀏覽器的原生 form 表單,如果不設置 enctype 屬性,那麼最終就會以 application/x-www-form-urlencoded 方式提交數據。請求類似於下面這樣(無關的請求頭在本文中都省略掉了):
POST HTTP/1.1 Content-Type:
application/x-www-form-urlencoded;charset=utf-8
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3

2、multipart/form-data
這又是一個常見的 POST 數據提交的方式。我們使用表單上傳文件時,必須讓 form 的 enctyped 等於這個值,下面是示例
POST HTTP/1.1
Content-Type:multipart/form-data; boundary=----
------
Content-Disposition: form-data; name="text"
title
------
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png
PNG ... content of chrome.png ...
--------

3、application/json
application/json 這個 Content-Type 作為響應頭大家肯定不陌生。實際上,現在越來越多的人把它作為請求頭,用來告訴服務端消息主體是序列化後的 JSON 字元串。由於 JSON 規范的流行,除了低版本 IE 之外的各大瀏覽器都原生支持 JSON.stringify,服務端語言也都有處理 JSON 的函數,使用 JSON 不會遇上什麼麻煩。
4、text/xml
它是一種使用 HTTP 作為傳輸協議,XML 作為編碼方式的遠程調用規范。
那麼Python在調用外部http請求時,post請求怎麼傳請求體呢?說實話樓主只實踐過【1、application/x-www-form-urlencoded】【2、multipart/form-data 】和【3、application/json】
一、application/x-www-form-urlencoded
import urllib

url = ""
body_value = {"package": "com.tencent.lian","version_code": "66" }
body_value = urllib.urlencode(body_value)
request = urllib2.Request(url, body_value)
request.add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()

二、multipart/form-data
需要利用python的poster模塊,安裝poster:pip install poster
代碼:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

url = ""
body_value = {"package": "com.tencent.lian","version_code": "66" }
register_openers()
datagen, re_headers = multipart_encode(body_value)
request = urllib2.Request(url, datagen, re_headers)
# 如果有請求頭數據,則添加請求頭
request .add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()

二、application/json
import json

url = ""
body_value = {"package": "com.tencent.lian","version_code": "66" }
register_openers()
body_value = json.JSONEncoder().encode(body_value)
request = urllib2.Request(url, body_value)
request .add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()

閱讀全文

與httpheaderpython相關的資料

熱點內容
python列表求交集 瀏覽:872
解壓包如何轉音頻 瀏覽:447
機明自動編程軟體源碼 瀏覽:325
php埠號設置 瀏覽:540
phperegreplace 瀏覽:320
androidgridview翻頁 瀏覽:537
ssh協議編程 瀏覽:634
如何開我的世界電腦伺服器地址 瀏覽:861
玄關pdf 瀏覽:609
程序員學習論壇 瀏覽:940
程序員的毒雞湯怎麼做 瀏覽:548
安卓怎麼降級軟體到手機 瀏覽:281
雲與伺服器入門書籍推薦產品 瀏覽:636
delphi編程助手 瀏覽:762
電腦遇到伺服器問題怎麼辦 瀏覽:515
加工中心編程結束方法 瀏覽:296
了解什麼是web伺服器 瀏覽:140
面向對象的編程的基本特徵 瀏覽:718
php定時執行任務linux 瀏覽:787
php數組中刪除元素 瀏覽:725