3.3. Cliente HTTP¶
3.3.1. Ejecución en script¶
Python le permite escribir y ejecutar vía script Python de un servidor HTTP de forma local.
Usted puede escribir y ejecutar un simple cliente HTTP desde linea de comando, con el siguiente codigo fuente:
import http.client
import sys
def run(http_server):
print("HTTP Client is starting...")
try:
# create a connection
connection = http.client.HTTPConnection(http_server, timeout=10)
while 1:
command = input(
'\nEnter a input command (example GET test.html, type "exit" to end it): '
)
command = command.split()
if command[0] == "exit": # type exit to end it
print("\nStopping web client....")
break
# request command to server
connection.request(command[0], command[1])
# get response from server
response = connection.getresponse()
# print server response and data
print(response.status, response.reason)
data_received = response.read()
print(data_received)
connection.close()
except KeyboardInterrupt:
print(" o <Ctrl-C> entered, stopping HTTP Client....")
connection.close()
if __name__ == "__main__":
"""Starting Python program"""
if not sys.argv[1:]:
print(
"Fatal: You forgot to include the URL like 127.0.0.1:8085 from the httpserver.py module on the command line."
)
print(f"Usage: python3 {sys.argv[0]} IP:PORT")
sys.exit(2)
else:
# get http server ip
http_server = sys.argv[1]
run(http_server)
Guarde el archivo httpclient.py
y ejecutandolo con el siguiente comando:
$ python httpclient.py
Importante
Usted puede descargar el código usado en esta sección haciendo clic en los
siguientes enlaces:
httpclient.py
.
Truco
Para ejecutar el código httpclient.py
, abra una consola de comando,
acceda al directorio donde se encuentra ambos programas:
leccion3/
└── httpclient.py
Si tiene la estructura de archivo previa, entonces ejecute el siguiente comando:
python3 httpclient.py
Ver también
Consulte la sección de lecturas suplementarias del entrenamiento para ampliar su conocimiento en esta temática.
¿Cómo puedo ayudar?
¡Mi soporte está aquí para ayudar!
Mi horario de oficina es de lunes a sábado, de 9 AM a 5 PM. GMT-4 - Caracas, Venezuela.
La hora aquí es actualmente 7:35 PM GMT-4.
Mi objetivo es responder a todos los mensajes dentro de un día hábil.