Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用http.client for API应用具有身份验证的代理_Python_Proxy_Bing_Bing Api_Http.client - Fatal编程技术网

Python 如何使用http.client for API应用具有身份验证的代理

Python 如何使用http.client for API应用具有身份验证的代理,python,proxy,bing,bing-api,http.client,Python,Proxy,Bing,Bing Api,Http.client,我正在尝试使用Bing的实体搜索API,但是我需要通过代理建立连接 我的公司给了我一份以下格式的委托书:http://username:password@webproxy.subdomain.website.com:8080' 我试过使用HTTPConnection.set_tunnel(主机,端口=None,头=None)但没有用。有人知道如何使用我提供的代理运行下面的Python查询吗 import http.client, urllib.parse import json proxy

我正在尝试使用Bing的实体搜索API,但是我需要通过代理建立连接

我的公司给了我一份以下格式的委托书:http://username:password@webproxy.subdomain.website.com:8080'

我试过使用HTTPConnection.set_tunnel(主机,端口=None,头=None)但没有用。有人知道如何使用我提供的代理运行下面的Python查询吗

import http.client, urllib.parse
import json


proxy = 'http://username:pwd@webproxy.subdomain.website.com:8080' 
subscriptionKey = 'MY_KEY_HERE'
host = 'api.cognitive.microsoft.com'
path = '/bing/v7.0/entities'
mkt = 'en-US'
query = 'italian restaurants near me'

params = '?mkt=' + mkt + '&q=' + urllib.parse.quote (query)

def get_suggestions ():
    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    conn = http.client.HTTPSConnection(host)
    conn.request("GET", path + params, None, headers)
    response = conn.getresponse()
    return response.read()

result = get_suggestions ()
print (json.dumps(json.loads(result), indent=4))
作为补充说明,我能够使用代理成功地运行以下内容

nltk.set_proxy('http://username:pwd@webproxy.subdomain.website.com:8080')
nltk.download('wordnet')

我最终使用了requests软件包,它们使得通过代理传递请求变得非常简单,下面的示例代码仅供参考:

    import requests

     proxies = {
    'http':  f"http://username:pwd@webproxy.subdomain.website.com:8080",
    'https': f"https://username:pwd@webproxy.subdomain.website.com:8080"
         }
    url = 'https://api.cognitive.microsoft.com/bing/v7.0/entities/'
    # query string parameters
    
   
    params = 'mkt=' + 'en-US' + '&q=' + urllib.parse.quote (query)

    
    # custom headers
    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    
    #start session
    session = requests.Session()
    #persist proxy across request
    session.proxies = proxies

    # make GET request
    r = session.get(url, params=params, headers=headers)





如果使用urlib2或请求,配置代理的最简单方法是设置HTTP_代理或HTTPS_代理环境变量:

export HTTPS_PROXY=https://user:pass@host:port
通过这种方式,库为您处理代理配置,如果您的代码在容器中运行,您可以在运行时传递该信息