'Simple socket library -- getting 400 error
Exercise 1: Change the socket program socket1.py to prompt the user for the URL so it can read any web page. You can use split('/') to break the URL into its component parts so you can extract the host name for the socket connect call. Add error checking using try and except to handle the condition where the user enters an improperly formatted or non-existent URL.
Exercise 2: Change your socket program so that it counts the number of characters it has received and stops displaying any text after it has shown 3000 characters. The program should retrieve the entire document and count the total number of characters and display the count of the number of characters at the end of the document.
This code should do both of these but for some reason it gives a '400 bad request' every time. I've written a similar code that works but it's a different module than import socket.
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
URL = input('Enter a URL: ')
hn = URL.split('/')
print(hn)
hn1 = hn[2]
print(hn1)
try:
mysock.connect((hn1, 80))
cmd = 'GET URL HTTP/1.0 /n/n'.encode()
mysock.send(cmd)
except:
print('ERROR 404: Not Found')
while True:
data = mysock.recv(3000)
if (len(data) < 1):
break
print(data.decode())
mysock.close()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
