no one
no one

Reputation: 25

sending https request with socket in python

I'm trying to send an https requests using socket in python, however I'm facing this error even when I tried to use the snippet in the documentations to test if the issue is in my code or maybe somewhere else. here is the snippet I took from the documentations :

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())

and here is the error I'm getting :

Traceback (most recent call last):
File "file.py", line 7, in <module>
with socket.create_connection((hostname, 443)) as sock:
AttributeError: __exit__

am I missing something here ? , I need to use sockets not requests or any other library

Upvotes: 0

Views: 942

Answers (1)

James Powis
James Powis

Reputation: 659

For python 2.7 you need to do the following:

import socket
import ssl

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

sock = socket.create_connection((hostname, 443))
ssock = context.wrap_socket(sock, server_hostname=hostname)
print(ssock.version())

Upvotes: 1

Related Questions