python構造器重載,python構造http請求_Python實現簡單的HTTP請求發送詳解

 2023-10-04 阅读 26 评论 0

摘要:代碼如下import?socketdef?clean_host(host):python構造器重載、"""Remove?leading?http://?and?trailing?/path_to_somewhere?in?host?name"""host?=?host.strip()prefixes?=?['http://']for?prefix?in?prefixes:python構造器,if?h

代碼如下

import?socket

def?clean_host(host):

python構造器重載、"""Remove?leading?http://?and?trailing?/path_to_somewhere?in?host?name"""

host?=?host.strip()

prefixes?=?['http://']

for?prefix?in?prefixes:

python構造器,if?host.lower().startswith(prefix):

host?=?host[len(prefix):]

slash?=?host.find('/')

if?slash>0:

python json?host?=?host[:slash]

return?host

def?get_ipv4_list(host,?port=80):

"""Return?the?list?of?ips?corresponding?to?given?host?and?port?number"""

類python、info?=?socket.getaddrinfo(host,?port)

return?[item[4][0]?for?item?in?info]

def?send_request(ip,?data,?remote_port=80,?local_port=2333,?bufsize=1024):

"""Send?data?to?give?ip?and?receive?response?from?the?server"""

qpython。sock?=?socket.socket(socket.AF_INET,?socket.SOCK_STREAM)

sock.connect((ip,?remote_port))

sock.send(data)

recv_data?=?[]

python爬蟲?while?True:

buf?=?sock.recv(bufsize)

if?not?buf:

break

python怎么用,recv_data?+=?[buf]

sock.close()

return?''.join(recv_data)

def?read_text(promp='>?',?promp2='~?'):

python數據結構、"""Read?in?text?from?stdin?terminted?by?EOF"""

text?=?[]

try:

while?True:

python post請求參數?if?not?text:

text?=?[raw_input(promp)+'\n']

else:

text?+=?[raw_input(promp2)+'\n']

python構造數據包?except?EOFError:

return?''.join(text)

return?''

def?http_app():

python請求網頁,remote_host?=?raw_input('Input?remote?host?name?(for?example?www.baidu.com):?')

remote_port?=?80

buf?=?raw_input('Input?remote?port?number?(default?80):?')

if?buf.isdigit()?and?0<=int(buf)<=65535:

remote_port?=?int(buf)

print?remote_host,?'at?port',?remote_port

print?'Resolving?host...'

ip_list?=?get_ipv4_list(clean_host(remote_host),?port=remote_port)

ip?=?ip_list[0]

print?'Using?ip?address',?ip

while?True:

data?=?read_text()

if?not?data:

break

print?'[REQUEST]'

print?data

response?=?send_request(ip,?data,?remote_port=remote_port)

print?'[REPONSE]'

print?response

if?__name__?==?'__main__':

print?'Running?http_app.?Press?Ctrl+C?to?quit'

while?True:

try:

http_app()

except?KeyboardInterrupt:

if?raw_input('Quit??').lower()?==?'n':

break

不過不知道是代碼哪里有問題導致返回的全都是Bad Request :(

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/113462.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息