예제 #1
0
 def login(self, username, password):
     connection = HttpConnection(self.flotrack_domain)
     connection.set_debuglevel(self.debug_level)
     connection.connect()
     # Configure login parameters (this is the content of the HTTP request)
     params = { "LoginForm[username]": username,
                "LoginForm[password]": password,
                "LoginForm[rememberMe]": 1, }
     encoded_params = url_encode(params)
     # Get the HTTP headers to use
     headers = self.get_default_headers(encoded_params)
     del headers["Cookie"]
     # Configure the cookie jar to store the login information
     cookie_request = HttpRequestAdapter(self.flotrack_domain, self.login_url,
                                         headers)
     self.cookie_jar.add_cookie_header(cookie_request)
     # Issue the HTTP request
     request = connection.request("POST", self.login_url, encoded_params, headers)
     response = connection.getresponse()
     if response.status == OK:
         return False
     if response.status == FOUND:
         response.read()
         response.info = lambda: response.msg
         # Extract the login cookies
         self.cookie_jar.extract_cookies(response, cookie_request)
         self.connection = connection
         return True
     raise Exception("Flotrack connection failed during login.")
예제 #2
0
    def send(self, config, outfile=None):
        con = HTTPConnection(config['host'], int(config['port']))
        con.set_debuglevel(self.debug)
        con.request(self.method, self.url, self.payload, self.headers)


        res = con.getresponse()
        if not self.hideResponseHeaders:
            print("\n\nStatus: " + str(res.status))
            print("Reason: " + str(res.reason))
            print("Headers: " + str(res.getheaders()))
        
        reply = None
        if outfile == None:
            reply = res.read()
            if not self.hideResponseHeaders:
                print("Reply:\n" + str(reply))
        else:
            with open(outfile, 'wb') as of:
                while True:
                    x = res.read(4096)
                    if len(x) == 0:
                        break
                    of.write(x)

        con.close()
        return res, reply
예제 #3
0
def request_info(operator, url_path, method, request=None):
    print "=" *70
    print "%s" % operator
    print "=" *70
    session = HTTPConnection("%s:%s" % (HOST, PORT))

    header = {
        "Content-Type": "application/json"
        }
    if method == "GET":
        if request:
            print url_path
            print request
            session.request("GET", url_path, request, header)
        else:
            print url_path
            session.request("GET", url_path, "", header)
    elif method == "POST":
        print url_path
        print request
        session.request("POST", url_path, request, header)
    elif method == "PUT":
        print url_path
        print request
        session.request("PUT", url_path, request, header)
    elif method == "DELETE":
        print url_path
        print request
        session.request("DELETE", url_path, request, header)



    session.set_debuglevel(4)
    print "----------"
    return json.load(session.getresponse())
예제 #4
0
class TWizardBind:
    def __init__(self, confPath=""):
        self.Conf = ConfigParser.ConfigParser()
        self.Conf.read(confPath)
        self.SocketHost = self.Conf.get("Service", "SocketHost")
        self.SocketPort = self.Conf.get("Service", "SocketPort")
        self.GetRequestParameters = self.Conf.get("Service", "GetRequestParameters")

    def __call__(self, queryText):
        print queryText.encode("utf-8")
        #try:
        self.Conn = HTTPConnection(self.SocketHost, self.SocketPort)
        self.Conn.set_debuglevel(5)
        self.Conn.request("GET", self.GetRequestParameters + urllib2.quote(queryText.encode("utf-8")))
        resp = self.Conn.getresponse()
        responseString = resp.read()
        self.Conn.close()
        print >> sys.stderr, "TWizardBind:Answer:", responseString
        jsonReplyObj = None
        try:
            jsonReplyObj = json.loads(responseString)
            print >> sys.stderr, "TWizardBind: Json object: ", jsonReplyObj
        except:
            print >> sys.stderr, "TWizardBind: can't parse json response"
        #except:
        #    print >> sys.stderr, "TWizardBind: Something wrong with connection"
        return jsonReplyObj
예제 #5
0
 def connect(self, url):
     try:
         connection = HTTPConnection(url)
         connection.set_debuglevel(self.http_debug)
         connection.connect()
         return connection
     except:
         error("Error connecting to '%s'" % url)
예제 #6
0
 def connect(self, url):
     try:
         connection = HTTPConnection(url)
         connection.set_debuglevel(self.http_debug)
         connection.connect()
         return connection
     except:
         raise Exception('Unable to connect to %r' % url)
예제 #7
0
    def _conectar_servico(self, servico, envio, resposta, ambiente=None):
        if ambiente is None:
            ambiente = self.ambiente
            
        self._servidor = CIDADE_WS[self.cidade][ambiente]['servidor']
        self._url = CIDADE_WS[self.cidade][ambiente]['url']

        self._soap_envio   = SOAPEnvio()
        self._soap_envio.metodo     = METODO_WS[servico]['metodo']
        self._soap_envio.envio      = envio

        self._soap_retorno = SOAPRetorno()
        self._soap_retorno.metodo     = METODO_WS[servico]['metodo']
        self._soap_retorno.resposta   = resposta
        
        if (servico == WS_NFSE_ENVIO_LOTE):
            self.certificado.prepara_certificado_arquivo_pfx()
            self.certificado.assina_xmlnfe(envio)

        con = HTTPConnection(self._servidor)
        con.set_debuglevel(10)
        
        con.request('POST', '/' + self._url, self._soap_envio.xml, self._soap_envio.header)
        resp = con.getresponse()

        # Dados da resposta salvos para possível debug
        self._soap_retorno.resposta.version  = resp.version
        self._soap_retorno.resposta.status   = resp.status
        self._soap_retorno.resposta.reason   = unicode(resp.reason.decode('utf-8'))
        self._soap_retorno.resposta.msg      = resp.msg
        self._soap_retorno.resposta.original = unicode(resp.read().decode('utf-8'))

        # Tudo certo!
        if self._soap_retorno.resposta.status == 200:
            self._soap_retorno.xml = self._soap_retorno.resposta.original
        #except Exception, e:
            #raise e
        #else:
        con.close()
        
        print()
        print()
        print()
        
        print(self._soap_envio.xml)
        
        print()
        print()
        print()
        
        print(por_acentos(self._soap_retorno.resposta.original))
        
        print()
        print()
        print()
        
        print(resposta.xml)
예제 #8
0
 def connect(self, url):
     """ Make connection."""
     try:
         connection = HTTPConnection(url)
         connection.set_debuglevel(self.http_debug)
         connection.connect()
         return connection
     except:
         raise Exception("Error connecting to '%s'" % url)
예제 #9
0
class ProductTest(TestCase):
  def setUp(self):
    self.conn = HTTPConnection('localhost', 5000, timeout=10)
    self.conn.set_debuglevel(DEBUG_LEVEL)

  def test_product_should_answer_200(self):
    self.conn.request(GET, '/product')
    response = self.conn.getresponse()
    self.assertEquals(response.status, 200)

  def test_product_id_should_answer_200(self):
    self.conn.request(GET, '/product/0')
    response = self.conn.getresponse()
    self.assertEquals(response.status, 200)
예제 #10
0
class GoogleSuggestions():
	def __init__(self):
		self.hl = "en"
		self.conn = None

	def prepareQuery(self):
		#GET /complete/search?output=toolbar&client=youtube-psuggest&xml=true&ds=yt&hl=en&jsonp=self.gotSuggestions&q=s
		self.prepQuerry = "/complete/search?output=toolbar&client=youtube&xml=true&ds=yt&"
		if self.hl is not None:
			self.prepQuerry = self.prepQuerry + "hl=" + self.hl + "&"
		self.prepQuerry = self.prepQuerry + "jsonp=self.getSuggestions&q="
		print "[MyTube - GoogleSuggestions] prepareQuery:",self.prepQuerry

	def getSuggestions(self, queryString):
		self.prepareQuery()
		if queryString is not "":
			query = self.prepQuerry + quote(queryString)
			try:
				self.conn = HTTPConnection("google.com")
				self.conn.set_debuglevel(1)
				self.conn.request("GET", query, "", {"Accept-Encoding": "UTF-8"})
			except (CannotSendRequest, gaierror, error):
				self.conn.close()
				print "[MyTube - GoogleSuggestions] Can not send request for suggestions"
				return None
			else:
				try:
					response = self.conn.getresponse()
				except BadStatusLine:
					self.conn.close()
					print "[MyTube - GoogleSuggestions] Can not get a response from google"
					return None
				else:
					if response.status == 200:
						data = response.read()
						header = response.getheader("Content-Type", "text/xml; charset=ISO-8859-1")
						charset = "ISO-8859-1"
						try:
							charset = header.split(";")[1].split("=")[1]
							print "[MyTube - GoogleSuggestions] Got charset %s" %charset
						except:
							print "[MyTube - GoogleSuggestions] No charset in Header, falling back to %s" %charset
						data = data.decode(charset).encode("utf-8")
						self.conn.close()
						return data
					else:
						self.conn.close()
						return None
		else:
			return None
예제 #11
0
    def connect(self, url):
        try:

            if self.proxy_host and self.proxy_port:
                LOG.info('proxy host: %s', self.proxy_host)
                LOG.info('proxy port: %d', self.proxy_port)
                connection = HTTPConnection(self.proxy_host, self.proxy_port)
            else:
                connection = HTTPConnection(url)
            connection.set_debuglevel(self.http_debug)
            if self.proxy_host and self.proxy_port:
                connection.set_tunnel(url, port=80)
            connection.connect()
            return connection
        except:
            raise Exception('Unable to connect to %r' % url)
예제 #12
0
 def __send__(self, params, url, method="POST"):
     try:
         from httplib import HTTPConnection
         from urllib import urlencode
         h = HTTPConnection(self.addr)
         h.set_debuglevel(self.debug_level)
         body = urlencode(params)
         if method == "GET":
             url += "?" + body
             body = None
         h.request(method, url, body)
         response = h.getresponse()
         return response
     except Exception as e:
         print "Got exception: {0}".format(e)
         return None
예제 #13
0
def request_info(url_path, method, request=None):
    session = HTTPConnection("%s:%s" % (HOST, PORT))

    header = {"Content-Type": "application/json"}
    if method == "GET":
        if request:
            session.request("GET", url_path, request, header)
        else:
            session.request("GET", url_path, "", header)
    elif method == "POST":
        session.request("POST", url_path, request, header)
    elif method == "PUT":
        session.request("PUT", url_path, request, header)
    elif method == "DELETE":
        session.request("DELETE", url_path, request, header)

    session.set_debuglevel(4)
    return json.load(session.getresponse())
예제 #14
0
def ms_translate(content_text):
    try:
        conn = HTTPConnection(host)
        conn.connect()
        conn.set_debuglevel(1)
        text = '[{"Text": "Hello"}]'
        conn.putrequest('POST', url_path)
        conn.putheader('Content-Length', len(text))
        conn.putheader('Ocp-Apim-Subscription-Key', subscriptionKey)
        conn.putheader('Content-type', 'application/json')
        conn.putheader('X-ClientTraceId', str(uuid.uuid4()))
        conn.endheaders()
        conn.send(text)
        output = json.loads(conn.getresponse())[0]['translations'][0]['text']
        print(output)
        return output

    except Exception as e:
        logging.error(e)
예제 #15
0
class THttpReply:
    def __init__(self, confPath=""):
        self.Conf = ConfigParser.ConfigParser()
        self.Conf.read(confPath)
        socketHost = self.Conf.get("THttpReplyConnection", "socket_host")
        socketPort = self.Conf.get("THttpReplyConnection", "socket_port")
        print socketHost, socketPort
        self.Conn = HTTPConnection(socketHost, socketPort)
        self.Conn.set_debuglevel(5)
        self.SendReply("Ping")

    def __call__(self):
        """put default action here"""

    def SendReply(self, replyStr):
        print >> sys.stderr, "Send reply:", replyStr.encode("utf-8")
        print >> sys.stdout, "Reply:", replyStr.encode("utf-8")
        self.Conn.request("GET", "/GetReply?ReqString=" + urllib2.quote(replyStr.encode("utf-8")))
        resp = self.Conn.getresponse()
        print >> sys.stderr, "Reply sent. Answer:", resp.read()
예제 #16
0
def request_info(url_path, method, request=None):
    session = HTTPConnection("%s:%s" % (HOST, PORT))

    header = {
        "Content-Type": "application/json"
        }
    if method == "GET":
        if request:
            session.request("GET", url_path, request, header)
        else:
            session.request("GET", url_path, "", header)
    elif method == "POST":
        session.request("POST", url_path, request, header)
    elif method == "PUT":
        session.request("PUT", url_path, request, header)
    elif method == "DELETE":
        session.request("DELETE", url_path, request, header)

    session.set_debuglevel(4)
    return json.load(session.getresponse())
예제 #17
0
    def request_info(self, operator, url_path, method, request, host):
        port = "8080"
        LOG.info("=" *70)
        LOG.info("%s" % operator)
        LOG.info("=" *70)
        session = HTTPConnection("%s:%s" % (host, port))

        header = {
            "Content-Type": "application/json"
            }
        if method == "GET":
            if request:
                LOG.info(url_path)
                LOG.info(request)
                session.request("GET", url_path, request, header)
            else:
                LOG.info(url_path)
                session.request("GET", url_path, "", header)
        session.set_debuglevel(4)
        LOG.info("----------")
        return json.load(session.getresponse())
예제 #18
0
파일: client.py 프로젝트: e0ipso/pAPITester
class ApplicationRequest(object):
  """Wrapper class around urllib2.Request to deal with the application data."""

  def __init__(self, settings):
    self.logger = pAPItester.util.TerminalLogger(settings['client']['verboseLevel'])
    # Set a default for the accept header if none is provided.
    try:
      settings['network']['headers']['Accept']
    except KeyError:
      settings['network']['headers']['Accept'] = '*/*'
    self.__settings = settings
    # Build the request url
    url = self.buildUrl()
    # Log a message.
    self.logger.log(settings['runtime']['method'] + ' ' + url, self.logger.ok)
    # Create the self.connection property according to the values of the configuration.
    try:
      if (settings['host']['url']['protocol'] == 'https'):
        self.connection = HTTPSConnection(settings['host']['url']['hostname'], settings['host']['url']['port'], settings['network']['privateKeyFile'], settings['network']['certFile'], True, settings['network']['timeout'], settings['network']['sourceAddress'])
      else:
        self.connection = HTTPConnection(settings['host']['url']['hostname'], settings['host']['url']['port'], True, settings['network']['timeout'], settings['network']['sourceAddress'])
    except HTTPException as e:
      sys.stderr.write("HTTP Error. Closing connection.\n")
      raise ApplicationException(e.str())
    self.connection.set_debuglevel(settings['client']['verboseLevel'])

  def buildUrl(self):
    """Builds the URL from the settings object."""
    port = self.__settings['host']['url']['port'] if self.__settings['host']['url']['port'] else (443 if self.__settings['host']['url']['protocol'] == 'https' else 80)
    return self.__settings['host']['url']['protocol'] + '://' + self.__settings['host']['url']['hostname'] + ':' + str(port) + self.buildRoute()

  def buildRoute(self):
    """Generate the absolute route for the request."""
    route = self.__settings['host']['url']['endpoint'].strip('/') + '/' + self.__settings['runtime']['route']
    return '/' + route.strip('/')

  def alterSettings(self, newSettings):
    """Replace the settings dict entirely by another one."""
    self.__settings = newSettings

  def request(self):
    """Make the request."""
    # Set the urlencode header if it's a POST request
    headers = self.__settings['network']['headers'];
    data = None;
    if self.__settings['runtime']['method'] == 'POST' or self.__settings['runtime']['method'] == 'PUT':
      headers['Content-type'] = 'application/x-www-form-urlencoded';
      # Read the JSON encoded data and convert it to URL encoded data.
      data = urllib.urlencode(json.loads(self.__settings['runtime']['data']));
    self.authentication()
    self.logger.log('Making a request to: ' + self.buildRoute(), self.logger.info)
    self.connection.request(self.__settings['runtime']['method'], self.buildRoute(), data, headers)
    self.logger.log('Getting a response.', self.logger.info)
    return self.getResponse()

  def authentication(self):
    if self.__settings['host']['authentication']['type'] == 'none':
      return
    elif self.__settings['host']['authentication']['type'] == 'basic':
      # base64 encode the username and password
      self.logger.log('Authenticating request with basic auth.', self.logger.info)
      auth_settings = self.__settings['host']['authentication']['settings'];
      auth = base64.encodestring(auth_settings['username'] + ':' + auth_settings['password']).replace('\n', '')
      self.__settings['network']['headers']['Authentication'] = auth

  def getResponse(self):
    """Get a response from the request."""
    response = self.connection.getresponse()
    messageType = self.logger.ok
    if int(int(response.status) / 100) != 2:
      messageType = self.logger.error
    self.logger.log(str(response.status) + ' ' + response.reason, messageType)
    return response

  def __del__(self):
    """Close the connection before object destruction."""
    self.logger.log('Closed connection with the server.', self.logger.info)
    self.connection.close()
예제 #19
0
def raw_pipeline(domain, pages, max_out_bound=4, method='GET', timeout=None, debuglevel=0):
    pagecount = len(pages)
    conn = HTTPConnection(domain, timeout=timeout)
    conn.set_debuglevel(debuglevel)
    respobjs = [None] * pagecount
    finished = [False] * pagecount
    responses = [None] * pagecount
    data = [None] * pagecount
    headers = {'Host': domain, 'Content-Length': 0, 'Connection': 'Keep-Alive'}

    while not all(finished):
        # Send
        out_bound = 0
        for i, page in enumerate(pages):
            if out_bound >= max_out_bound:
                break
            elif page and not finished[i] and respobjs[i] is None:
                if debuglevel > 0:
                    print 'Sending request for %r...' % (page,)
                conn._HTTPConnection__state = _CS_IDLE # FU private variable!
                conn.request(method, page, None, headers)
                respobjs[i] = conn.response_class(conn.sock, strict=conn.strict, method=conn._method)
                out_bound += 1

        # Try to read a response
        for i, resp in enumerate(respobjs):
            if resp is None:
                continue
            if debuglevel > 0:
                print 'Retrieving %r...' % (pages[i],)
            out_bound -= 1
            skip_read = False
            resp.begin()
            if debuglevel > 0:
                print '    %d %s' % (resp.status, resp.reason)
            if 200 <= resp.status < 300:
                # Ok
                data[i] = resp.read()
                cookie = resp.getheader('Set-Cookie')
                if cookie is not None:
                    headers['Cookie'] = cookie
                skip_read = True
                finished[i] = True
                responses[i] = respobjs[i]
                respobjs[i] = None
            elif 300 <= resp.status < 400:
                # Redirect
                loc = resp.getheader('Location')
                respobjs[i] = None
                parsed = loc and urlparse.urlparse(loc)
                if not parsed:
                    # Missing or empty location header
                    data[i] = (resp.status, resp.reason)
                    finished[i] = True
                elif parsed.netloc != '' and parsed.netloc != domain:
                    # Redirect to another domain
                    data[i] = (resp.status, resp.reason, loc)
                    finished[i] = True
                else:
                    path = urlparse.urlunparse(parsed._replace(scheme='',netloc='',fragment=''))
                    if debuglevel > 0:
                        print '  Updated %r to %r' % (pages[i],path)
                    pages[i] = path
            elif resp.status >= 400:
                # Failed
                data[i] = (resp.status, resp.reason)
                finished[i] = True
                responses[i] = respobjs[i]
                respobjs[i] = None
            if resp.will_close:
                # Connection (will be) closed, need to resend
                conn.close()
                if debuglevel > 0:
                    print '  Connection closed'
                for j, f in enumerate(finished):
                    if not f and respobjs[j] is not None:
                        if debuglevel > 0:
                            print '  Discarding out-bound request for %r' % (pages[j],)
                        respobjs[j] = None
                break
            elif not skip_read:
                resp.read() # read any data
            if any(not f and respobjs[j] is None for j,f in enumerate(finished)):
                # Send another pending request
                break
        else:
            break # All respobjs are None?
    return responses, data
def http_download_get_request(uri, hdrs = {}):
	conn = HTTPConnection('localhost',8804)
	conn.set_debuglevel(1)
	conn.request("GET", uri, '',hdrs)
	resp = conn.getresponse()
	return resp
예제 #21
0
def raw_pipeline(domain,
                 pages,
                 max_out_bound=4,
                 method='GET',
                 timeout=None,
                 debuglevel=0):
    pagecount = len(pages)
    conn = HTTPConnection(domain, timeout=timeout)
    conn.set_debuglevel(debuglevel)
    respobjs = [None] * pagecount
    finished = [False] * pagecount
    responses = [None] * pagecount
    data = [None] * pagecount
    headers = {'Host': domain, 'Content-Length': 0, 'Connection': 'Keep-Alive'}

    while not all(finished):
        # Send
        out_bound = 0
        for i, page in enumerate(pages):
            if out_bound >= max_out_bound:
                break
            elif page and not finished[i] and respobjs[i] is None:
                if debuglevel > 0:
                    print 'Sending request for %r...' % (page, )
                conn._HTTPConnection__state = _CS_IDLE  # FU private variable!
                conn.request(method, page, None, headers)
                respobjs[i] = conn.response_class(conn.sock,
                                                  strict=conn.strict,
                                                  method=conn._method)
                out_bound += 1

        # Try to read a response
        for i, resp in enumerate(respobjs):
            if resp is None:
                continue
            if debuglevel > 0:
                print 'Retrieving %r...' % (pages[i], )
            out_bound -= 1
            skip_read = False
            resp.begin()
            if debuglevel > 0:
                print '    %d %s' % (resp.status, resp.reason)
            if 200 <= resp.status < 300:
                # Ok
                data[i] = resp.read()
                cookie = resp.getheader('Set-Cookie')
                if cookie is not None:
                    headers['Cookie'] = cookie
                skip_read = True
                finished[i] = True
                responses[i] = respobjs[i]
                respobjs[i] = None
            elif 300 <= resp.status < 400:
                # Redirect
                loc = resp.getheader('Location')
                respobjs[i] = None
                parsed = loc and urlparse.urlparse(loc)
                if not parsed:
                    # Missing or empty location header
                    data[i] = (resp.status, resp.reason)
                    finished[i] = True
                elif parsed.netloc != '' and parsed.netloc != domain:
                    # Redirect to another domain
                    data[i] = (resp.status, resp.reason, loc)
                    finished[i] = True
                else:
                    path = urlparse.urlunparse(
                        parsed._replace(scheme='', netloc='', fragment=''))
                    if debuglevel > 0:
                        print '  Updated %r to %r' % (pages[i], path)
                    pages[i] = path
            elif resp.status >= 400:
                # Failed
                data[i] = (resp.status, resp.reason)
                finished[i] = True
                responses[i] = respobjs[i]
                respobjs[i] = None
            if resp.will_close:
                # Connection (will be) closed, need to resend
                conn.close()
                if debuglevel > 0:
                    print '  Connection closed'
                for j, f in enumerate(finished):
                    if not f and respobjs[j] is not None:
                        if debuglevel > 0:
                            print '  Discarding out-bound request for %r' % (
                                pages[j], )
                        respobjs[j] = None
                break
            elif not skip_read:
                resp.read()  # read any data
            if any(not f and respobjs[j] is None
                   for j, f in enumerate(finished)):
                # Send another pending request
                break
        else:
            break  # All respobjs are None?
    return responses, data
def http_download_get_request(uri, hdrs = {}):
	conn = HTTPConnection('localhost',8804)
	conn.set_debuglevel(1)
	conn.request("GET", uri, '',hdrs)
	resp = conn.getresponse()
	return resp
예제 #23
0
 def _get_connection(self):
     conn = HTTPConnection(self._host)
     conn.set_debuglevel(0)
     return conn
예제 #24
0
 def _get_connection(self):
     conn = HTTPConnection(self._host)
     conn.set_debuglevel(0)
     return conn