Search code examples
pythonsocketshttphttps

How can I fix 301 error using python sockets


I am just beginning to learn how to use sockets in python. I am trying to create a get request to "python.org" but I keep on getting "301" error. If anyone knows why please help.

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
        request = 'GET / HTTP/1.1\r\nHost:%s\r\n\r\n' % hostname
        ssock.send(request.encode())
        response = ssock.recv(6000)
        print(response)

EDIT: I am currently getting this response

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

Can anyone help with this error?

Got it working with this code:

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:

    try:
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    except:
        None

    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
        request = 'GET / HTTP/1.1\r\nHost:%s\r\n\r\n' % hostname
        ssock.send(request.encode())
        response = ssock.recv(6000)
        print(response)

Solution

  • 301 HTTP code is Moved Permanently not an error. For this resources, you need use with another link (current is /, it define in first line GET / HTTP). It define in your response http_response .