class Http2Client: """HTTP/2 client class.""" def __init__(self, host, port, certificate, cert_key, cert_password=None): """ Initialization method. :param host: str Host URI to connect to. :param certificate: str Name along with path of the client certificate file. :param cert_key: str Name along with path of the client certificate key. :param cert_password: str Password for the client certificate, if any. """ self._host = host self._port = port self._certificate = certificate self._cert_key = cert_key self._cert_password = cert_password self._context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) self._context.load_cert_chain(certfile=self._certificate, keyfile=self._cert_key, password=self._cert_password) self._connection = HTTPConnection(host=self._host, port=self._port, secure=True, ssl_context=self._context) def do_get(self, uri): """ GET request handler. :param uri: str URI value. :return: str Response of GET. """ self._connection.request(method='GET', url=uri) response = self._connection.get_response() LOGGER.info(response.status, response.reason) return response.read() def do_post(self, uri, data, headers=None): """ POST request handler. :param uri: str :param data: object :param headers: dict :return: """ if not headers: headers = {'Content-Type': 'text/plain'} self._connection.request(method='POST', url=uri, headers=headers, body=data) response = self._connection.get_response() return response
def send_push(registration_id: str, title: str, body: str) -> None: path = '/3/device/{0}'.format(registration_id) request_headers = { 'apns-expiration': '0', 'apns-priority': '10', 'apns-topic': constants.APN.BUNDLE_ID, 'apns-push-type': 'alert', 'authorization': 'bearer {0}'.format(JWTToken.get_token().decode('ascii')) } payload_data = { 'aps': { 'alert': { 'title': title, 'body': body }, "sound": "default" } } payload = json.dumps(payload_data).encode('utf-8') conn = HTTPConnection('api.push.apple.com:443') conn.request( 'POST', path, payload, headers=request_headers ) _ = conn.get_response()
def get_or_create(cls, user_id): user = cls.query.get(user_id) if not user: steam_api_connection = HTTPConnection("api.steampowered.com") query_parameters = { "key": config["steam_api_key"], "steamids": user_id } steam_api_connection.request( "GET", "/ISteamUser/GetPlayerSummaries/v0001/?{}".format( urlencode(query_parameters))) steam_response = json.loads( steam_api_connection.get_response().read().decode("utf-8")) steam_data = steam_response['response']['players']['player'][ 0] or {} user = cls(id=user_id, name=steam_data.get("realname", None), nickname=steam_data.get("personaname", None), avatar_url=steam_data.get("avatarfull", None), steam_profile_url=steam_data.get("profileurl", None)) db.session.add(user) db.session.commit() return user
def searchDate(headers, url): time.sleep(5) print("请求url" + url) c = HTTPConnection('www.toutiao.com:443') first = c.request("GET", url, headers=headers) first_response = c.get_response(first) text = first_response.read(decode_content=False) jsonObject = json.loads(text) # 转json对象可以不用转码 array = jsonObject['data'] print(jsonObject) max_behot_time = "" try: print("下次时间%s" % (jsonObject['next']['max_behot_time'])) max_behot_time = jsonObject['next']['max_behot_time'] if max_behot_time == 0 or max_behot_time == "0": raise BaseException except BaseException: print("递归") return searchDate(headers, url) print("递归" + url) for i in array: print("标题:%s,播放量:%s,评论:%s" % (i['title'], i['detail_play_effective_count'], i['comments_count'])) return max_behot_time
def push(self, token, alert_title='', alert_body='', badge=1, sound='default'): """ 发送单个设备 :param token:设备 :param alert_title:弹出的消息title加粗 :param alert_body:弹出的消息title加粗 :param badge:红点数字 :param sound:声音 :return: """ token = self.handle_token(token) payload = { 'aps': { 'alert': alert_title, 'body': alert_body, 'content-available': 1, 'sound': sound, 'badge': badge, } } conn = HTTPConnection(self.api_url, ssl_context=tls.init_context( cert=self.cert, cert_password=self.cert_password)) conn.request('POST', self.get_api_path(token), body=json.dumps(payload), headers=self.headers) resp = conn.get_response() return self.make_response(resp)
class ScrapyApiDownloaderMiddleware(object): def __init__(self): self.api_connection = HTTPConnection('api.amemv.com:443') temp_path = os.path.join(os.getcwd(), 'args.json') with open(temp_path, 'r') as f: self.args = json.loads(f.read()) pass @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): user_id = request.meta.get('user_id') args = self.args[request.url] query = args['query'] query['user_id'] = user_id headers = args['headers'] str = urlencode(query, safe='!*();:@&=+$,/?#[]') #设置安全字符以防止过多编码 arr = urlparse(request.url) url = arr.path + '?' + str print('注意检查url编码', url) url = "/aweme/v1/aweme/post/?max_cursor=0&user_id=71912868448&count=20&retry_type=no_retry&mcc_mnc=46003&iid=104243110108&device_id=61908178454&ac=wifi&channel=wandoujia_aweme&aid=1128&app_name=aweme&version_code=400&version_name=4.0.0&device_platform=android&ssmix=a&device_type=EVA-AL10&device_brand=HUAWEI&language=zh&os_api=26&os_version=8.0.0&uuid=861533036745840&openudid=0f772e0fa9d36257&manifest_version_code=400&resolution=1080*1792&dpi=480&update_version_code=4002&_rticket=1582426486876&ts=1582426486&js_sdk_version=1.6.4&as=a1855ef5e6b7fea9c14922&cp=ee76ef556a155e99e1%5BwIa&mas=013ea13c774313309341e958c883be52094c4c9c2c8cc69c86a666" self.api_connection.request('GET', url, headers=headers) response = self.api_connection.get_response() result = response.read() return TextResponse(url=url, status=200, request=request, headers=headers, body=result, encoding='utf-8') def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
def request(args): conn = HTTPConnection(args.url.host, args.url.port) conn.request(args.method, args.url.path, args.body, args.headers) response = conn.get_response() log.debug('Response Headers:\n%s', pformat(response.headers)) ctype, charset = get_content_type_and_charset(response) data = response.read().decode(charset) if 'json' in ctype: data = pformat(json.loads(data)) return data
def makerequest(port, active_timeout): hyper.tls._context = hyper.tls.init_context() hyper.tls._context.check_hostname = False hyper.tls._context.verify_mode = hyper.compat.ssl.CERT_NONE conn = HTTPConnection('localhost:{0}'.format(port), secure=True) try: # delay after sending the first request # so the H2 session active timeout triggers # Then the next request should fail req_id = conn.request('GET', '/') time.sleep(active_timeout) response = conn.get_response(req_id) req_id = conn.request('GET', '/') response = conn.get_response(req_id) except Exception: print('CONNECTION_TIMEOUT') return print('NO_TIMEOUT')
def send_notification(host, url, device_token, payload, url_headers): conn = HTTPConnection(host) complete_url = url + device_token conn.request('POST', complete_url, payload, url_headers) respsone = conn.get_response() response_body = respsone.read() if not response_body: print(f'\nSuccess sending notification to: {device_token}') else: print(f'\nFailed to send notification to: {device_token}') print(f'Failure reason: {get_failure_reason(response_body)}')
def send_notification(device, notification): if not notifications['apns_key_id']: return "" authorization_jwt = create_apns_jwt() notification_json = json_dumps(notification.to_apns_json()) headers = { 'authorization': f'bearer {authorization_jwt}', 'apns-expiration': str(int(time() + APNS_EXPIRATION)), 'apns-priority': '5', 'apns-topic': notifications['web_apn_id'] } url = f'/3/device/{device.device_id}' conn = HTTPConnection(APNS_SERVER) conn.request('POST', url, body=notification_json, headers=headers) server.logger.info( f'Notification (APNS) dispatched {notification.uuid} -> {device.device_id}' ) resp = conn.get_response() response_status = resp.status response_body = resp.read() # Handle errors in APNS notifications. Apple explicitly states # that response will be exactly 200 is successful, any other # response indicates otherwise if response_status != 200: try: reason = json_loads(response_body)['reason'] # If reason is 'BadDeviceToken' this means the user has likely # unsubscribed so we'll remove their device subscription if reason == 'BadDeviceToken': db.session.delete(device) db.session.commit() except ValueError: reason = "unknown" if bugsnag.configuration.api_key is not None: bugsnag.notify(Exception("APNS dispatch error"), meta_data={"apns_rejection": { "reason": reason }}) server.logger.error( f'Notification (APNS) rejected {notification.uuid} -> {device.device_id}:\n{reason}' )
def global_uid(url): try: arr = urlparse(url) headers = {'User-Agent': 'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14'} connection = HTTPConnection(arr.netloc+':443') connection.request('GET', arr.path, headers=headers) res = connection.get_response().read().decode('utf-8') temp = re.search(r'/(\d+)\?', res) print('匹配到', temp.group(1)) return temp.group(1) except Exception as e: print(e) return None
def send_POST(self, response): c = HTTPConnection(self.url) c.request('POST', '/post', body=response) resp = c.get_response() # If you wish to see what was POST-ed, uncomment line below # print resp.read() #return (resp.status) if resp.status == 200: print " JSON POST-ed successfully" else: print " JSON POST failed with status %d!" % resp.status self.error = True return
def get_acgnx_index(): conn = HTTPConnection("share.acgnx.se", port=443) headers = build_headers() conn.request('GET', '/', headers=headers) resp = conn.get_response() for cookie in resp.headers['set-cookie']: headers['cookie'] = headers['cookie'] + cookie.split(';')[0] + "; " print(headers['cookie']) conn.request('GET', '/', headers=headers) resp = conn.get_response() response_js = resp.read() key_index = response_js.find('jump|') value_index = response_js.find("|escape") key = response_js[key_index + 5:key_index + 5 + 32] value = response_js[value_index - 32:value_index] new_cookie = key + "=" + value + ";" headers['cookie'] = headers['cookie'] + new_cookie print(headers['cookie']) conn.request('GET', '/', headers=headers) resp = conn.get_response() return resp.read()
def send_push(input): topic = getOrRaise(input, "topic") token = getOrRaise(input, "token_hex") apnsPayload = getOrRaise(input, "apns") environment = getEnvironment(input) if environment in devEnvironments: host = "api.development.push.apple.com" pushCert = "cert/pushcert_dev.p12" if environment in prodEnvironments: host = "api.push.apple.com" pushCert = "cert/pushcert_prod.p12" print(host) method = "POST" path = "/3/device/{}".format(token) # Build headers headers = {"apns-topic": topic} if input.get("apns-push-type"): headers["apns-push-type"] = input.get("apns-push-type") if input.get("apns-id"): headers["apns-id"] = input.get("apns-id") if input.get("apns-expiration"): headers["apns-expiration"] = input.get("apns-expiration") if input.get("apns-priority"): headers["apns-priority"] = input.get("apns-priority") if input.get("apns-collapse-id"): headers["apns-collapse-id"] = input.get("apns-collapse-id") conn = HTTPConnection( host=host, secure=True, port=443, ssl_context=init_context(cert=pushCert) ) conn.request( method=method, url=path, body=json.dumps(apnsPayload).encode("utf-8"), headers=headers ) return conn.get_response()
def request(args): if not args.h2: conn = HTTPConnection(args.url.host, args.url.port, secure=args.url.secure) else: # pragma: no cover conn = HTTP20Connection(args.url.host, args.url.port, secure=args.url.secure) conn.request(args.method, args.url.path, args.body, args.headers) response = conn.get_response() log.debug('Response Headers:\n%s', pformat(response.headers)) ctype, charset = get_content_type_and_charset(response) data = response.read() return data
def request(args): if not args.h2: conn = HTTPConnection( args.url.host, args.url.port, secure=args.url.secure ) else: # pragma: no cover conn = HTTP20Connection( args.url.host, args.url.port, secure=args.url.secure ) conn.request(args.method, args.url.path, args.body, args.headers) response = conn.get_response() log.debug('Response Headers:\n%s', pformat(response.headers)) ctype, charset = get_content_type_and_charset(response) data = response.read() return data
def login(self): conn = HTTPConnection('api.fshare.vn:443') data = { 'user_email': self.email, 'password': self.password, 'app_key': "L2S7R6ZMagggC5wWkQhX2+aDi467PPuftWUMRFSn" } login_request = conn.request('POST', '/api/user/login/', body=json.dumps(data)) response = conn.get_response(login_request) login_data = json.loads(response.read().decode('utf-8')) self.token = login_data['token'] cookie = login_data['session_id'] self.s.cookies.set('session_id', cookie) return data
def makerequest(port): hyper.tls._context = hyper.tls.init_context() hyper.tls._context.check_hostname = False hyper.tls._context.verify_mode = hyper.compat.ssl.CERT_NONE conn = HTTPConnection('localhost:{0}'.format(port), secure=True) sites = {'/'} request_ids = [] for site in sites: request_id = conn.request('GET', url=site) request_ids.append(request_id) # get responses for req_id in request_ids: response = conn.get_response(req_id) print(getResponseString(response))
class ScrapydouyinDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. def __init__(self): self.api_connection = HTTPConnection('api.amemv.com:443') temp_path = os.path.join(os.getcwd(), 'args.json') with open(temp_path, 'r') as f: self.args = json.loads(f.read()) pass @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): keyword = request.meta.get('keyword') args = self.args[request.url] query = args['query'] query['keyword'] = keyword headers = args['headers'] str = urlencode(query, safe='!*();:@&=+$,/?#[]') #设置安全字符以防止过多编码 arr = urlparse(request.url) url = arr.path + '?' + str print('注意检查url编码', url) self.api_connection.request('GET', url, headers=headers) response = self.api_connection.get_response() result = response.read() return TextResponse(url=url, status=200, request=request, headers=headers, body=result, encoding='utf-8') def process_response(self, request, response, spider): return response def process_exception(self, request, exception, spider): pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
def check_url(main_url, path_url): ''' Use requests to get URL, and return HTTP status code. @param main_url: hostname with port. @param path_url: path url. @return: HTTP response status code, or None if request failed. @return: Parsed HTTP response, or None if request failed. ''' print("main_url =", main_url) print("path_url =", path_url) status_code = None table_sections = None for i in range(0, __RETRY_MAX): print("Check url count = {0}".format(i)) try: connection = HTTPConnection(main_url) connection_id = connection.request('GET', path_url) response = connection.get_response(connection_id) print("response.status =", response.status) status_code = response.status if status_code != HTTPStatus.OK: raise Exception("Retrieve data failed.") html_data = BeautifulSoup(response.read(), "html.parser") print("HTML title =", html_data.title) table_sections = html_data.find_all( "table", {"class": "clamp-list condensed"}) print("Find table_sections =", len(table_sections)) if len(table_sections) < 4: raise Exception("Retrieve data failed.") break except Exception as e: print("Check url failed, Count = {0}, Exception = {1}".format( i, e)) if i + 1 == __RETRY_MAX: raise e else: sleep((i + 1) * 10) return status_code, table_sections
def makerequest(port, _url): hyper.tls._context = hyper.tls.init_context() hyper.tls._context.check_hostname = False hyper.tls._context.verify_mode = hyper.compat.ssl.CERT_NONE conn = HTTPConnection('localhost:{0}'.format(port), secure=True) sites = {'/'} responses = [] request_ids = [] for site in sites: request_id = conn.request('GET', url=_url) request_ids.append(request_id) # get responses for req_id in request_ids: response = conn.get_response(req_id) body = response.read() print(getResponseString(response)) print(body.decode('utf-8'))
def test_http2_server_push(launch): with launch("./examples/app.py") as engine: conn = HTTPConnection('127.0.0.1:30371', enable_push=True, secure=False) conn.request('GET', '/promise') response = conn.get_response() pathes = [] for push in conn.get_pushes( ): # all pushes promised before response headers pathes.append(push.path) print(push.path) assert b'/hello' in pathes assert b'/test' in pathes data = response.read() assert b'"data": "JSON"' in data print(data)
def send_push_notification(device_token, data, production=True, is_retry=False): t = get_token() path = '/3/device/{0}'.format(device_token) token = t['token'] request_headers = { 'apns-expiration': '0', 'apns-priority': '5', 'apns-topic': BUNDLE_ID, 'apns-push-type': 'background', 'authorization': 'bearer {0}'.format(token) } payload_data = {'aps': {'content-available': 1}, 'data': data} payload = json.dumps(payload_data).encode('utf-8') if production: conn = HTTPConnection('api.push.apple.com:443') else: conn = HTTPConnection('api.sandbox.push.apple.com:443') conn.request('POST', path, payload, headers=request_headers) resp = conn.get_response() print(resp.status) if resp.status >= 300: resp_error = resp.read() print(resp_error) # remove token if not is_retry and resp.status == 400: j = json.loads(resp_error.decode('ascii')) if 'reason' in j and j['reason'] == 'BadDeviceToken': print('gonna try development environment iOS') send_push_notification(device_token, data, production=not production, is_retry=True)
def push(self, title, body, device_token, isProduction): file = open(self.APNS_AUTH_KEY) secret = file.read() token = jwt.encode({ 'iss': self.TEAM_ID, 'iat': time.time() }, secret, algorithm=self.ALGORITHM, headers={ 'alg': self.ALGORITHM, 'kid': self.APNS_KEY_ID, }) path = '/3/device/{0}'.format(device_token) request_headers = { 'apns-expiration': '0', 'apns-priority': '10', 'apns-topic': self.BUNDLE_ID, 'authorization': 'bearer {0}'.format(token.decode('ascii')) } if isProduction: conn = HTTPConnection('api.push.apple.com:443') else: conn = HTTPConnection('api.development.push.apple.com:443') payload_data = { 'aps': { 'alert': { 'title': title, 'body': body }, 'badeg': 1, 'sound': 'default' } } payload = json.dumps(payload_data).encode('utf-8') conn.request('POST', path, payload, headers=request_headers) resp = conn.get_response() print(resp.status) print(resp.read())
def download(url): try: if url is None or not isinstance(url, six.types.StringTypes): return False, "No url was given to download" if verbose: print("[Process: {}] - Downloading url {} ".format( multiprocessing.current_process(), url)) url_p = urlparse.urlparse(url) conn = HTTPConnection(url_p.hostname) conn.request('GET', '{}?{}'.format(url_p.path, url_p.query)) resp = conn.get_response() if Constants.picture_serialization: with open(Constants.get_output_for_url(url), "wb") as f: f.write(resp.read()) else: # For performance measurement resp.read() return True, except Exception as e: return False,
def download(url): """ TO-DO - finish hyper api connection c = HTTPConnection(graphai.facebook.FACEBOOK_GRAPH_URL) stream_id = c.request('GET', graph.get_me_query_path()) resp = c.get_response() print resp.headers print resp.status print resp.read() # Using requests and hyper s = requests.Session() s.mount(graphai.facebook.FACEBOOK_GRAPH_URL, HTTP20Adapter()) r = s.get(graph.get_me_query_path()) r2 = s.get(graph.get_me_query_path()) """ try: if url is None or not isinstance(url, six.types.StringTypes): return False, "No url was given to download" if verbose: print("[Process: {}] - Downloading url {} ".format( multiprocessing.current_process(), url)) url_p = urlparse.urlparse(url) conn = HTTPConnection(url_p.hostname) conn.request('GET', '{}?{}'.format(url_p.path, url_p.query)) resp = conn.get_response() if Constants.picture_serialization: with open(Constants.get_output_for_url(url), "wb") as f: f.write(resp.read()) else: # For performance measurement resp.read() return True, except Exception as e: return False,
def makerequest(port): hyper.tls._context = hyper.tls.init_context() hyper.tls._context.check_hostname = False hyper.tls._context.verify_mode = hyper.compat.ssl.CERT_NONE conn = HTTPConnection('localhost:{0}'.format(port), secure=True) # Fetch the object twice so we know at least one time comes from cache # Exploring timing options sites = ['/bigfile', '/bigfile'] responses = [] request_ids = [] for site in sites: request_id = conn.request('GET', url=site) request_ids.append(request_id) # get responses for req_id in request_ids: response = conn.get_response(req_id) body = response.read() cl = response.headers.get('Content-Length')[0] print("Content length = {}\r\n".format(int(cl))) print("Body length = {}\r\n".format(len(body))) error = 0 if chr(body[0]) != 'a': error = 1 print("First char {}".format(body[0])) i = 1 while i < len(body) and not error: error = chr(body[i]) != 'b' if error: print("bad char {} at {}".format(body[i], i)) i = i + 1 if not error: print("Content success\r\n") else: print("Content fail\r\n")
def single_push(self, token, alert, badge=1): """ 发送单个设备 :param token:设备 :param alert:弹出的消息 :param badge:红点数字 :return: """ token = self.handle_token(token) payload = { 'aps': { 'alert': alert, 'sound': 'default', 'badge': badge, } } conn = HTTPConnection(self.api_url, ssl_context=tls.init_context(cert=self.cert)) conn.request('POST', self.get_api_path(token), body=json.dumps(payload), headers=self.headers) resp = conn.get_response() return self.make_response(resp)
from hyper import HTTPConnection, tls headers = { ":authority": "api.amemv.com", "cookie": "install_id=104243110108, ttreq=1$0982c95be39210c4cedda04ccd70095de17c7de9, d_ticket=91c7682f2d9cc9bd821075f286b97c9ecb138, odin_tt=a7056720e8585b5dcc7c9bf3aed08349078974999caa4844ca9881e7225ddde80516c82854a8f5095d66d36308d5858a, sid_guard=846d26a0aed08ec2496c90e73a227d66%7C1582358865%7C5184000%7CWed%2C+22-Apr-2020+08%3A07%3A45+GMT, uid_tt=c3d97367d0d47449cbf301f7e5e0a8e9, sid_tt=846d26a0aed08ec2496c90e73a227d66, sessionid=846d26a0aed08ec2496c90e73a227d66", "accept-encoding": "gzip", "x-ss-req-ticket": "1582358887070", "x-tt-token": "00846d26a0aed08ec2496c90e73a227d663fc8db9044e03eff2b8d105d0a250f6b05505d72588779153e7b025fec6b029c41", "sdk-version": "1", "x-ss-tc": "0", "user-agent": "com.ss.android.ugc.aweme/400 (Linux; U; Android 8.0.0; zh_CN; EVA-AL10; Build/HUAWEIEVA-AL10; Cronet/58.0.2991.0)", "x-khronos": "1582358887", "x-gorgon": "0192cb7ea5883f4b2021f11674d12a3162e6870a7a457100d2", "x-pods": "" } # url="/aweme/v1/user/?user_id=71912868448&retry_type=no_retry&mcc_mnc=46003&iid=104243110108&device_id=61908178454&ac=wifi&channel=wandoujia_aweme&aid=1128&app_name=aweme&version_code=400&version_name=4.0.0&device_platform=android&ssmix=a&device_type=EVA-AL10&device_brand=HUAWEI&language=zh&os_api=26&os_version=8.0.0&uuid=861533036745840&openudid=0f772e0fa9d36257&manifest_version_code=400&resolution=1080*1792&dpi=480&update_version_code=4002&_rticket=1582295017514&ts=1582295016&js_sdk_version=1.6.4&as=a1354ea4083e8e67cf0677&cp=eeede6568bf84f7fe1Wo_w&mas=0175542def29312fc1860a1de9f3ed4088ecec6c0c66c6ec6ca61c" # response = requests.get(url, headers=headers).text # url="/aweme/v2/comment/list/?aweme_id=6786492441756257536&cursor=0&count=20&ts=1582295195&js_sdk_version=1.6.4&app_type=normal&manifest_version_code=400&_rticket=1582295195798&ac=wifi&device_id=61908178454&iid=104243110108&mcc_mnc=46003&os_version=8.0.0&channel=wandoujia_aweme&version_code=400&device_type=EVA-AL10&language=zh&uuid=861533036745840&resolution=1080*1792&openudid=0f772e0fa9d36257&update_version_code=4002&app_name=aweme&version_name=4.0.0&os_api=26&device_brand=HUAWEI&ssmix=a&device_platform=android&dpi=480&aid=1128&as=a175de84ebd93e585f0266&cp=eb9feb59b8fb458be1KmSq&mas=01a125260b232b9e3bb3af6c498847a5106c6c4c0c66ac1caca6cc" # url="/aweme/v1/general/search/single/?keyword=%E5%A4%A7%E7%8B%BC%E7%8B%97%E9%83%91%E5%BB%BA%E9%B9%8F%E5%A4%AB%E5%A6%87&offset=0&count=10&is_pull_refresh=0&hot_search=0&latitude=24.352902&longitude=118.033784&ts=1582334159&js_sdk_version=1.6.4&app_type=normal&manifest_version_code=400&_rticket=1582334160365&ac=wifi&device_id=61908178454&iid=104243110108&mcc_mnc=46003&os_version=8.0.0&channel=wandoujia_aweme&version_code=400&device_type=EVA-AL10&language=zh&uuid=861533036745840&resolution=1080*1792&openudid=0f772e0fa9d36257&update_version_code=4002&app_name=aweme&version_name=4.0.0&os_api=26&device_brand=HUAWEI&ssmix=a&device_platform=android&dpi=480&aid=1128&as=a19518258fdc0e00d00266&cp=8bcced51fd005701e1KmSq&mas=011645234873c6a138cb1ee205243d7f386c6c4c0c0c260c0ca60c" url = "/aweme/v1/general/search/single/?keyword=%E5%A4%A7%E7%8B%BC%E7%8B%97%E9%83%91%E5%BB%BA%E9%B9%8F%E5%A4%AB%E5%A6%87&offset=0&count=10&is_pull_refresh=0&hot_search=0&latitude=24.352849&longitude=118.033782&ts=1582358886&js_sdk_version=1.6.4&app_type=normal&manifest_version_code=400&_rticket=1582358887072&ac=wifi&device_id=61908178454&iid=104243110108&mcc_mnc=46003&os_version=8.0.0&channel=wandoujia_aweme&version_code=400&device_type=EVA-AL10&language=zh&uuid=861533036745840&resolution=1080*1792&openudid=0f772e0fa9d36257&update_version_code=4002&app_name=aweme&version_name=4.0.0&os_api=26&device_brand=HUAWEI&ssmix=a&device_platform=android&dpi=480&aid=1128&as=a115ee7596b6deb1800655&cp=ee66ea5a6309571de1[mIq&mas=0139aecceef69eb8f522479b562ffa1773acac6c0c0c1c8c46a626" c = HTTPConnection('api.amemv.com:443') c.request('GET', url, headers=headers) response = c.get_response() print(response.read())
# Open a connection the APNS server conn = HTTPConnection('api.development.push.apple.com:443') payload_data = { 'aps': { 'event_type' : 'MESSAGE' }, 'text0' : 'Prova', 'lyber_id': '2904' } payload = json.dumps(payload_data).encode('utf-8') # Send our request conn.request( 'POST', path, payload, headers=request_headers ) resp = conn.get_response() print(resp.status) print(resp.read()) # If we are sending multiple requests, use the same connection #payload_data = { # 'aps': { 'alert' : 'You have no chance to survive. Make your time.' } #} #payload = json.dumps(payload_data).encode('utf-8') #conn.request( # 'POST', # path, # payload, # headers=request_headers
import json from hyper import HTTPConnection conn = HTTPConnection('localhost:8080', secure=True) conn.request('GET', '/') resp = conn.get_response() index_data = json.loads(resp.read().decode("utf8")) for _id in index_data[:1000]: book_details_path = "/book?id={}".format(_id) request_id = conn.request('GET', book_details_path) if request_id: # we're using HTTP2 response = conn.get_response(request_id) else: # we're using HTTP 1.1 response = conn.get_response() print(response) body = json.loads(response.read().decode("utf8")) print(body)
from hyper import HTTPConnection import re response_format = '{0:23} {1:3} {2}' def get_favicon_url(country): return 'static-' + country + '.zacdn.com:443' countries = ['hk', 'id', 'my', 'ph', 'sg', 'th', 'tw', 'vn'] urls = ['dynamic.zacdn.com:443'] for country in countries: urls.append(get_favicon_url(country)) for url in urls: connection = HTTPConnection(url) uri = '/images/favicon.png' if 'dynamic' not in url else '/85QZRTbD9wWnOgwv9jg-XG3npz0=/fit-in/236x345/filters:quality(95):fill(ffffff)/http://static.sg.zalora.net/p/zalora-3327-380904-1.jpg' try: connection.request('GET', uri) response = connection.get_response() print response_format.format( url, response.status, 'passed' if response.status == 200 else 'failed') response.close() except: print response_format.format(url, 'N/A', 'failed')
# to use hyper in MacOS, you have to upgrade openssl version # http://stackoverflow.com/questions/18752409/updating-openssl-in-python-2-7 from hyper import HTTPConnection import re response_format = '{0:23} {1:3} {2}' def get_favicon_url(country): return 'static-' + country +'.zacdn.com:443' countries = ['hk', 'id', 'my', 'ph', 'sg', 'th', 'tw', 'vn'] urls = ['dynamic.zacdn.com:443'] for country in countries: urls.append(get_favicon_url(country)) for url in urls: connection = HTTPConnection(url) uri = '/images/favicon.png' if 'dynamic' not in url else '/85QZRTbD9wWnOgwv9jg-XG3npz0=/fit-in/236x345/filters:quality(95):fill(ffffff)/http://static.sg.zalora.net/p/zalora-3327-380904-1.jpg' try: connection.request('GET', uri) response = connection.get_response() print response_format.format(url, response.status, 'passed' if response.status == 200 else 'failed') response.close() except: print response_format.format(url, 'N/A', 'failed')
# code, errmsg = reason # print(token,errmsg) # # """ 使用http2连接一直连接不上apns服务器 """ from hyper import HTTPConnection, tls import json token = 'ac16e5344c0de2a626e2d3789a18c054e380060fb3165779a173a1d4bd8f905b' payload = { 'aps': { 'alert': '测试推送', 'sound': 'default', 'badge': 1, } } headers = { "apns-topic": 'com.csdigit.movesx', } conn = HTTPConnection('api.development.push.apple.com:443', ssl_context=tls.init_context(cert_path=apn_dev_cert_path)) conn.request('POST', '/3/device/%s' % token, body=json.dumps(payload), headers=headers) resp = conn.get_response() d = resp.status print(d)
from hyper import HTTPConnection c = HTTPConnection('localhost:8080') c.request('GET', '/') print(c.get_response())
def test_http2(): conn = HTTPConnection('api.development.push.apple.com:443') conn.request('POST', '/3/device/123') resp = conn.get_response() return resp.read()