网络客户端 python http

时间:2021-02-14 19:19:22

标签: python sockets http webclient

我在 python 中有这段代码,它使用套接字显示 http 响应。此时我可以识别状态代码,并打印消息。但现在我想准备我的代码来处理不同的 http 响应,特别是一个,比如 302,女巫被永久移动,所以我的代码需要为新位置创建一个新的 GET 方法。

这样做的最佳方法是什么?

PS:不能使用 http 库

from socket import * 

#response dictionary
my_dict={200:'ok',302:'moved',404:'error'}

from socket import * 

#ask inputs
target_host = input("Enter the url: ")#localhost
target_dir = input("Enter the  path: ")#/index.html or /
target_port = input("Enter the port number: ")#80

# create a socket object 
client = socket(AF_INET, SOCK_STREAM)  # create an INET (IPv4), STREAMing socket (TCP)
 
# connect the client 
client.connect((target_host,int(target_port)))  
 
# send some data 
request = "GET /%s HTTP/1.1\r\nHost:%s\r\n\r\n" % (target_dir, target_host)

#Send data to the socket.
client.send(request.encode())  

# receive some data 
data = b''
while True: #while data
    buffer = client.recv(2048) #recieve a 2048 bytes data from socket
    if not buffer or buffer=='\n': #no more data, break
        break
    data += buffer #concatenate buffer data
    
client.close() #close connection

status = -1  #init status
word = data.split() #split data in a array of words
try:
    status = int(word[1])#cast data[i] 
except:
    pass

#print data
print("status code: " , status)
print("server reply: " , data.decode())

1 个答案:

答案 0 :(得分:0)

您可以使用 socket.gethostbyname 直接获取服务器 ip,然后创建到所需 ip 的连接,而不是解析多个重定向,然后使用最终 url 的 dns 解析获取服务器 ip。

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
ip_addr = socket.gethostbyname('google.com')
s.connect((ip_addr, 443))  # using https port 

您可以在浏览器中输入变量 ip_addr 中的值并检查,它会被重定向到 google.com