Python socket module. Connecting to an HTTP proxy then performing a GET request on an external resource

后端 未结 2 692
梦毁少年i
梦毁少年i 2021-01-07 06:36

To begin with, I understand there are other modules such as Requests that would be better suited and simpler to use, but I want to use the socket module to better understand

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 07:17

    Python 3 requires the request to be encoded. Thus, expanding on David's original code, combined with Steffens answer, here is the solution written for Python 3:

    def connectThroughProxy():
        headers = """GET http://www.example.org HTTP/1.1
                    Host: www.example.org\r\n\r\n"""
    
        host = "192.97.215.348" #proxy server IP
        port = 8080              #proxy server port
    
        try:
            s = socket.socket()
            s.connect((host,port))
            s.send(headers.encode('utf-8'))
            response = s.recv(3000)
            print (response)
            s.close()
        except socket.error as m:
           print (str(m))
           s.close()
           sys.exit(1) 
    

    This allows me to connect to the example.org host through my corporate proxy (at least for non SSL/TLS connections).

提交回复
热议问题