python类HTTPConnection()的实例源码

xmlrpclib.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def make_connection(self, host):
        #return an existing connection if possible.  This allows
        #HTTP/1.1 keep-alive.
        if self._connection and host == self._connection[0]:
            return self._connection[1]

        # create a HTTP connection object from a host descriptor
        chost, self._extra_headers, x509 = self.get_host_info(host)
        #store the host argument along with the connection object
        self._connection = host, httplib.HTTPConnection(chost)
        return self._connection[1]

    ##
    # Clear any cached connection object.
    # Used in the event of socket errors.
    #
Backup_Mysql.py 文件源码 项目:BackManager 作者: linuxyan 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def request_api(params_dict):
    httpClient = None
    try:
        params = urllib.urlencode(params_dict)
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        httpClient = httplib.HTTPConnection(api_url, int(api_port), timeout=5)
        httpClient.request("POST", api_path, params, headers)
        response = httpClient.getresponse()
        status = response.status
        if str(status) != '200':
            data = {'status':500,'auth':'failed'}
        else:
            data = eval(response.read())
            data['status'] = status
        return data
    except Exception, e:
        print e
        data = {'status':500,'auth':'failed'}
        return data
    finally:
        if httpClient:
            httpClient.close()
oss_api.py 文件源码 项目:mongodb_backup_script 作者: hxt168 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_connection(self, tmp_host=None):
        host = ''
        port = 80
        if not tmp_host:
            tmp_host = self.host
        host_port_list = tmp_host.split(":")
        if len(host_port_list) == 1:
            host = host_port_list[0].strip()
        elif len(host_port_list) == 2:
            host = host_port_list[0].strip()
            port = int(host_port_list[1].strip())
        if self.is_security or port == 443:
            self.is_security = True
            if sys.version_info >= (2, 6):
                return httplib.HTTPSConnection(host=host, port=port, timeout=self.timeout)
            else:
                return httplib.HTTPSConnection(host=host, port=port)
        else:
            if sys.version_info >= (2, 6):
                return httplib.HTTPConnection(host=host, port=port, timeout=self.timeout)
            else:
                return httplib.HTTPConnection(host=host, port=port)
darkTouch.py 文件源码 项目:darkc0de-old-stuff 作者: tuwid 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def Fuzz(entry):
    try:
        entry = "/" + entry
        connection = httplib.HTTPConnection(site)
        connection.request("GET",entry)
        response = connection.getresponse()
        if response.status == 200:
            str = 'http://'+site+entry
            print "Found : %s " % (str)
            found.append(str)
        else:
            pass
    except(KeyboardInterrupt,SystemExit):
            raise
    except:
            pass
proxy.py 文件源码 项目:darkc0de-old-stuff 作者: tuwid 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def request(self, method, url, body=None, headers={}):
        # Request is called before connect, so can interpret url and get
        # real host/port to be used to make CONNECT request to proxy
        proto, rest = urllib.splittype(url)

        if proto is None:
            raise ValueError, "unknown URL type: %s" % url

        # Get host
        host, rest = urllib.splithost(rest)

        # Try to get port
        host, port = urllib.splitport(host)

        # If port is not defined try to get from proto
        if port is None:
            try:
                port = self._ports[proto]
            except KeyError:
                raise ValueError, "unknown protocol for: %s" % url

        self._real_host = host
        self._real_port = int(port)

        httplib.HTTPConnection.request(self, method, url, body, headers)
server.py 文件源码 项目:darkc0de-old-stuff 作者: tuwid 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def senddata(self):
        filename = "output.txt"
        fileit = open(filename, 'r')
        done = 0
        while not done:
            output = fileit.readline()
            if output != "":
                # 'text' is the value needed to be past to the php script to put in db
                # the form name is text which is a textarea
                params = urllib.urlencode({'text': output})
                headers = {"Content-type": "application/x-www-form-urlencoded",
                                "Accept": "text/plain"}
                conn = httplib.HTTPConnection(linecache.getline('info.txt', 1))
                conn.request("POST", "/filewrite.php", params, headers)
                response = conn.getresponse()
                print response.status, response.reason
                data = response.read()        
            else:
                done = 1
        fileit.close()
        return True
utils.py 文件源码 项目:abusehelper 作者: Exploit-install 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(
        self,
        host,
        port=None,
        strict=None,
        timeout=None,
        certfile=None,
        keyfile=None,
        require_cert=True,
        ca_certs=None
    ):
        httplib.HTTPConnection.__init__(self, host, port, strict, timeout)

        self.certfile = certfile
        self.keyfile = keyfile
        self.require_cert = require_cert
        self.ca_certs = ca_certs
utils.py 文件源码 项目:abusehelper 作者: Exploit-install 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def connect(self):
        httplib.HTTPConnection.connect(self)

        with ca_certs(self.ca_certs) as certs:
            self.sock = ssl.wrap_socket(
                self.sock,
                certfile=self.certfile,
                keyfile=self.keyfile,
                cert_reqs=ssl.CERT_REQUIRED if self.require_cert else ssl.CERT_NONE,
                ca_certs=certs
            )

        if self.require_cert:
            hostname = self.host if not self._tunnel_host else self._tunnel_host
            cert = self.sock.getpeercert()
            match_hostname(cert, hostname)
general.py 文件源码 项目:veneer-py 作者: flowmatters 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def retrieve_json(self,url):
        '''
        Retrieve data from the Veneer service at the given url path.

        url: Path to required resource, relative to the root of the Veneer service.
        '''
        if PRINT_URLS:
            print("*** %s ***" % (url))

        if self.protocol=='file':
            text = open(self.prefix+url+self.data_ext).read()
        else:
            conn = hc.HTTPConnection(self.host,port=self.port)
            conn.request('GET',quote(url+self.data_ext))
            resp = conn.getresponse()
            text = resp.read().decode('utf-8')
            #text = urlopen(self.base_url + quote(url+self.data_ext)).read().decode('utf-8')

        text = self._replace_inf(text)
        if PRINT_ALL:
            print(json.loads(text))
            print("")
        return json.loads(text)
sendDataToThingSpeak.py 文件源码 项目:Micro-bit 作者: ArcherHuang 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def post_to_thingspeak(payload):
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
    not_connected = 1
    while (not_connected):
        try:
            conn = httplib.HTTPConnection("api.thingspeak.com:80")
            conn.connect()
            not_connected = 0
        except (httplib.HTTPException, socket.error) as ex:
            print "Error: %s" % ex
            time.sleep(10)  # sleep 10 seconds

    conn.request("POST", "/update", payload, headers)
    response = conn.getresponse()
    print( response.status, response.reason, payload, time.strftime("%c"))
    data = response.read()
    conn.close()
sendDataToMCS.py 文件源码 项目:Micro-bit 作者: ArcherHuang 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def post_to_mcs(payload):
    headers = {"Content-type": "application/json", "deviceKey": deviceKey}
    not_connected = 1
    while (not_connected):
        try:
            conn = httplib.HTTPConnection("api.mediatek.com:80")
            conn.connect()
            not_connected = 0
        except (httplib.HTTPException, socket.error) as ex:
            print "Error: %s" % ex
            time.sleep(10)  # sleep 10 seconds

    conn.request("POST", "/mcs/v2/devices/" + deviceId + "/datapoints", json.dumps(payload), headers)
    response = conn.getresponse()
    print( response.status, response.reason, json.dumps(payload), time.strftime("%c"))
    data = response.read()
    conn.close()
xmlrpclib.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def make_connection(self, host):
        #return an existing connection if possible.  This allows
        #HTTP/1.1 keep-alive.
        if self._connection and host == self._connection[0]:
            return self._connection[1]

        # create a HTTP connection object from a host descriptor
        chost, self._extra_headers, x509 = self.get_host_info(host)
        #store the host argument along with the connection object
        self._connection = host, httplib.HTTPConnection(chost)
        return self._connection[1]

    ##
    # Clear any cached connection object.
    # Used in the event of socket errors.
    #
http_core.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_connection(self, uri, headers=None):
    """Opens a socket connection to the server to set up an HTTP request.

    Args:
      uri: The full URL for the request as a Uri object.
      headers: A dict of string pairs containing the HTTP headers for the
          request.
    """
    connection = None
    if uri.scheme == 'https':
      if not uri.port:
        connection = httplib.HTTPSConnection(uri.host)
      else:
        connection = httplib.HTTPSConnection(uri.host, int(uri.port))
    else:
      if not uri.port:
        connection = httplib.HTTPConnection(uri.host)
      else:
        connection = httplib.HTTPConnection(uri.host, int(uri.port))
    return connection
blockade.py 文件源码 项目:tecken 作者: mozilla-services 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def block_http(whitelist):
    def whitelisted(self, host, *args, **kwargs):
        try:
            string_type = basestring
        except NameError:
            # python3
            string_type = str
        if isinstance(host, string_type) and host not in whitelist:
            logger.warning('Denied HTTP connection to: %s' % host)
            raise MockHttpCall(host)
        logger.debug('Allowed HTTP connection to: %s' % host)
        return self.old(host, *args, **kwargs)

    whitelisted.blockade = True

    if not getattr(httplib.HTTPConnection, 'blockade', False):
        logger.debug('Monkey patching httplib')
        httplib.HTTPConnection.old = httplib.HTTPConnection.__init__
        httplib.HTTPConnection.__init__ = whitelisted
selenium.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def do_command(self, verb, args):
        conn = http_client.HTTPConnection(self.host, self.port, timeout=self.http_timeout)
        try:
            body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode('utf-8'))
            for i in range(len(args)):
                body += '&' + unicode(i+1) + '=' + \
                        urllib_parse.quote_plus(unicode(args[i]).encode('utf-8'))
            if (None != self.sessionId):
                body += "&sessionId=" + unicode(self.sessionId)
            headers = {
                "Content-Type":
                "application/x-www-form-urlencoded; charset=utf-8"
            }
            conn.request("POST", "/selenium-server/driver/", body, headers)

            response = conn.getresponse()
            data = unicode(response.read(), "UTF-8")
            if (not data.startswith('OK')):
                raise Exception(data)
            return data
        finally:
            conn.close()
shellshock_tester_plugin.py 文件源码 项目:midip-sslyze 作者: soukupa5 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def process_task(self, server_connectivity_info, plugin_command, option_dict=None):
        if option_dict and 'path' in option_dict.keys():
            path = str(option_dict['path'])
        else:
            path = '/'
        if server_connectivity_info.port == 80:
            conn = httplib.HTTPConnection(server_connectivity_info.ip_address,server_connectivity_info.port)
        elif server_connectivity_info.port == 443:
            conn = httplib.HTTPSConnection(server_connectivity_info.ip_address,server_connectivity_info.port,context=ssl._create_unverified_context())
        else:
            raise ValueError("ShellshockTesterPlugin: Can\'t make test for this port {0}".format(server_connectivity_info.port))

        try:
            conn.connect()
        except Exception as e:
            raise ValueError("ShellshockTesterPlugin: Connection error for port {0}. {1}".format(server_connectivity_info.port,str(e)))
        else:
            conn.request("GET", path, "", {'User-Agent': '() { :; }; echo; echo Vulnerable to CVE-2014-6271'})
            response = conn.getresponse()

        return ShellshockTesterResult(server_connectivity_info, plugin_command, option_dict, self.is_vulnerable(response))
warequest.py 文件源码 项目:whatsapp-rest-webservice 作者: svub 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def sendRequest(host, port, path, headers, params, reqType="GET"):

        params = urlencode(params)


        path = path + "?"+ params if reqType == "GET" and params else path

        if len(headers):
            logger.debug(headers)
        if len(params):
            logger.debug(params)

        logger.debug("Opening connection to %s" % host);
        conn = httplib.HTTPSConnection(host ,port) if port == 443 else httplib.HTTPConnection(host ,port)

        logger.debug("Sending %s request to %s" % (reqType, path))
        conn.request(reqType, path, params, headers);

        response = conn.getresponse()
        return response
UpnpPunch.py 文件源码 项目:zeronet-debian 作者: bashrc 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _send_soap_request(location, upnp_schema, control_url, soap_message):
    """
    Send out SOAP request to UPnP device and return a response.
    """
    headers = {
        'SOAPAction': (
            '"urn:schemas-upnp-org:service:{schema}:'
            '1#AddPortMapping"'.format(schema=upnp_schema)
        ),
        'Content-Type': 'text/xml'
    }
    conn = httplib.HTTPConnection(location.hostname, location.port)
    conn.request('POST', control_url, soap_message, headers)

    response = conn.getresponse()
    conn.close()

    return _parse_for_errors(response)
Torrent_ip_checker.py 文件源码 项目:FunUtils 作者: HoussemCharf 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def work(IP):
        conn = httplib.HTTPConnection("www.iknowwhatyoudownload.com/en/peer/?ip="+IP)
        conn.request("GET","/")
        response = conn.getresponse()
        data =response.read()
        soup = BS(data,"html.parser")
        table = soup.find('tbody')
        rows = table.findAll('tr')
        for tr in rows:
            cols = tr.findAll('td')
            Begin,End,Category,title,size=[c.text for c in cols]
            RESULT+="\n"+Begin+" "+Category+" "+title+" "+size
        toplevel = Toplevel()
        label= Label(toplevel,text=RESULT,height=0,width=100)
        label.pack()
        print RESULT
test_responces.py 文件源码 项目:rheostatic 作者: waylan 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def assertResponse(self, app, method, url, status=None, headers=None, content=None):
        host, port = 'localhost', 80
        http_client_intercept.install()
        add_wsgi_intercept(host, port, app)
        client = http_lib.HTTPConnection(host, port)
        client.request(method, url)
        response = client.getresponse()

        if status is not None:
            self.assertEqual(response.status, status)

        headers = headers or {}
        for k, v in headers.items():
            self.assertEqual(response.getheader(k), v)

        if content is not None:
            self.assertEqual(response.read(), content)

        client.close()
        remove_wsgi_intercept(host, port)
        http_client_intercept.uninstall()
util.py 文件源码 项目:nojs 作者: chrisdickinson 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def DoesUrlExist(url):
  """Determines whether a resource exists at the given URL.

  Args:
    url: URL to be verified.

  Returns:
    True if url exists, otherwise False.
  """
  parsed = urlparse.urlparse(url)
  try:
    conn = httplib.HTTPConnection(parsed.netloc)
    conn.request('HEAD', parsed.path)
    response = conn.getresponse()
  except (socket.gaierror, socket.error):
    return False
  finally:
    conn.close()
  # Follow both permanent (301) and temporary (302) redirects.
  if response.status == 302 or response.status == 301:
    return DoesUrlExist(response.getheader('location'))
  return response.status == 200
httprelayclient.py 文件源码 项目:PiBunny 作者: tholum 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self, target):
        # Target comes as protocol://target:port/path
        self.target = target
        proto, host, path = target.split(':')
        host = host[2:]
        self.path = '/' + path.split('/', 1)[1]
        if proto.lower() == 'https':
            #Create unverified (insecure) context
            try:
                uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                self.session = HTTPSConnection(host,context=uv_context)
            except AttributeError:
                #This does not exist on python < 2.7.11
                self.session = HTTPSConnection(host)
        else:
            self.session = HTTPConnection(host)
        self.lastresult = None
download.py 文件源码 项目:PythonP2PBotnet 作者: jhoward321 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def download(host, port, filepath):
    conn = httplib.HTTPConnection(host, port)
    conn.request("GET", "/"+filepath)

    fp = open(filepath, 'wb')

    resp =conn.getresponse()

    #read 4096 bytes at a time
    block_size = 4096
    buffer = resp.read(block_size)
    while(buffer):
        fp.write(buffer)
        buffer = resp.read(block_size)

    fp.close()
    conn.close()

#use: python download.py [host] [port] [filepath]
response.py 文件源码 项目:api-gateway-demo-sign-python 作者: aliyun 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_http_response(self):
        if self.__port is None or self.__port == "":
            self.__port = 80
        try:
            self.__connection = httplib.HTTPConnection(self.parse_host(), self.__port)
            self.__connection.connect()
            post_data = None
            if self.get_content_type() == constant.CONTENT_TYPE_FORM and self.get_body():
                post_data = urllib.urlencode(self.get_body())
            else:
                post_data = self.get_body()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=post_data,
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response.status, response.getheaders(), response.read()
        except Exception as e:
            return None, None, None
        finally:
            self.__close_connection()
proxylib.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def create_http_request(self, method, url, headers, body, timeout, **kwargs):
        scheme, netloc, path, query, _ = urlparse.urlsplit(url)
        if netloc.rfind(':') <= netloc.rfind(']'):
            # no port number
            host = netloc
            port = 443 if scheme == 'https' else 80
        else:
            host, _, port = netloc.rpartition(':')
            port = int(port)
        if query:
            path += '?' + query
        if 'Host' not in headers:
            headers['Host'] = host
        if body and 'Content-Length' not in headers:
            headers['Content-Length'] = str(len(body))
        ConnectionType = httplib.HTTPSConnection if scheme == 'https' else httplib.HTTPConnection
        connection = ConnectionType(netloc, timeout=timeout)
        connection.request(method, path, body=body, headers=headers)
        response = connection.getresponse()
        return response
selenium.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def do_command(self, verb, args):
        conn = http_client.HTTPConnection(self.host, self.port, timeout=self.http_timeout)
        try:
            body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode('utf-8'))
            for i in range(len(args)):
                body += '&' + unicode(i+1) + '=' + \
                        urllib_parse.quote_plus(unicode(args[i]).encode('utf-8'))
            if (None != self.sessionId):
                body += "&sessionId=" + unicode(self.sessionId)
            headers = {
                "Content-Type":
                "application/x-www-form-urlencoded; charset=utf-8"
            }
            conn.request("POST", "/selenium-server/driver/", body, headers)

            response = conn.getresponse()
            data = unicode(response.read(), "UTF-8")
            if (not data.startswith('OK')):
                raise Exception(data)
            return data
        finally:
            conn.close()
check_local_network.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _check_ipv6_host(host):
    try:
        conn = httplib.HTTPConnection(host, 80, timeout=5)
        header = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",
                  "accept":"application/json, text/javascript, */*; q=0.01",
                  "accept-encoding":"gzip, deflate, sdch",
                  "accept-language":'en-US,en;q=0.8,ja;q=0.6,zh-CN;q=0.4,zh;q=0.2',
                  "connection":"keep-alive"
                  }
        conn.request("HEAD", "/", headers=header)
        response = conn.getresponse()
        if response.status:
            return True
        else:
            return False
    except Exception as e:
        return False
Echonify.py 文件源码 项目:Scripts 作者: Echonify 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def write(obj):
    try:
        conn = httplib.HTTPConnection("127.0.0.1", localPort)
        headers = {
            "Content-Type": "application/json",
            "Echonify-SecurityToken": securityToken,
            "Echonify-FlowDirection": "outbound"
        }
        data = json.dumps(obj)
        conn.request("POST", "/", data, headers=headers)
        response = conn.getresponse()
        if response.status <> 200:
            return False
        return True
    finally:
        conn.close
Echonify.py 文件源码 项目:Scripts 作者: Echonify 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def writeStream(fileName, streamId):
    try:
        conn = httplib.HTTPConnection("127.0.0.1", localPort)
        conn.connect()
        conn.putrequest("POST", "/")
        conn.putheader("Transfer-Encoding", "chunked")
        conn.putheader("Content-Type", "application/octet-stream")
        conn.putheader("Echonify-SecurityToken", securityToken)
        conn.putheader("Echonify-FlowDirection", "outbound")
        conn.putheader("Echonify-StreamId", streamId)
        conn.endheaders()
        with open(fileName, 'rb') as f:
            while True:
                chunk = f.read(2048)
                if not chunk:
                    break
                conn.send("%s\r\n" % hex(len(chunk))[2:])
                conn.send("%s\r\n" % chunk)
        conn.send("0\r\n\r\n")
        response = conn.getresponse()
        if response.status <> 200:
            return False
        return True
    finally:
        conn.close
k8s.py 文件源码 项目:paas-tools 作者: imperodesign 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _delete_pod(self, name, namespace):
        headers = {'Content-Type': 'application/json'}
        con_dest_pod = httplib.HTTPConnection(self.target+":"+self.port)
        con_dest_pod.request('DELETE', '/api/'+self.apiversion+'/namespaces/' +
                             namespace+'/pods/'+name, headers=headers, body=POD_DELETE)
        resp = con_dest_pod.getresponse()
        reason = resp.reason
        status = resp.status
        data = resp.read()
        con_dest_pod.close()
        if not 200 <= status <= 299:
            errmsg = "Failed to delete Pod: {} {} - {}".format(
                status, reason, data)
            raise RuntimeError(errmsg)
        for _ in xrange(5):
            status, data, reason = self._get_pod(name, namespace)
            if status != 404:
                time.sleep(1)
                continue
            break
        if status != 404:
            errmsg = "Failed to delete Pod: {} {} - {}".format(
                status, reason, data)
            raise RuntimeError(errmsg)


问题


面经


文章

微信
公众号

扫码关注公众号