Reputation: 1
I have implemented HTTP methods (GET,HEAD,POST and OPTIONS), that work fine. But unable to implement DELETE method. Here is code:
import socket
# creating socket instance
# socket.AF_INET = IPV4
# type=socket.SOCK_STREAM = TCP
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
# target ip address and port
ip_address = '127.0.0.1'
port = 80 # Connection port
# instance requesting for connection to the specified address and port
try:
s.connect((ip_address,port))
# Send the DELETE request
request ="DELETE /fmweb/test.html HTTP/1.1\r\n"
request = request + "Accept: text/html\r\n\r\n"
response = s.send(request.encode())
response = s.recv(4096)
print(response.decode())
except:
print("Error")
finally:
s.close()
I tried with different configuration of IIS by adding DELETE verb, but failed to work
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 20 Jul 2023 15:49:47 GMT
Connection: close
Content-Length: 334
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>
Upvotes: 0
Views: 63
Reputation: 74
The issue you are facing is likely related to the HTTP request you are sending. The "Bad Request - Invalid Hostname" error indicates that the server doesn't recognize the hostname in your request.
The problem is in the request line. When you use the DELETE method, you typically don't include the full URL in the request line; instead, you just include the path to the resource you want to delete. The correct format for the DELETE request would be:
DELETE /fmweb/test.html HTTP/1.1\r\n
Host: 127.0.0.1\r\n
Accept: text/html\r\n\r\n
Here, we have added a "Host" header to specify the hostname (in this case, it's the IP address) the request is directed to. This header is required for HTTP/1.1 requests, and it helps the server identify the intended host.
Additionally, it's always a good practice to include the "Host" header in HTTP/1.1 requests. So, make sure to include it along with other required headers.
Modify your code as follows:
import socket
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
ip_address = '127.0.0.1'
port = 80
try:
s.connect((ip_address, port))
request = "DELETE /fmweb/test.html HTTP/1.1\r\n"
request += "Host: 127.0.0.1\r\n"
request += "Accept: text/html\r\n\r\n"
s.send(request.encode())
response = s.recv(4096)
print(response.decode())
except Exception as e:
print("Error:", e)
finally:
s.close()
Hope this helped!
Upvotes: 1