2013-08-30 146 views
0

我已經在web服務中使用了下面的python代碼,但是在這裏我的站點url是包含https的。所以如果我使用http,那麼它會在Web服務運行時給出「未找到方法」錯誤,並且如果我使用https,那麼此代碼不起作用。如何在python中使用https服務使用web服務

任何人都可以讓我知道如何使用https解決此問題。

import urllib 
uid = username 
pwd = psw 
params = urllib.urlencode({ 
    'uid': uid, 
    'pwd': pwd, 
data = urllib.urlopen(url, params).read() 
print data 

或告訴我任何其他方法,我們可以使用Web服務。

在此先感謝!

+0

您是否試過'urllib2'? http://docs.python.org/2/library/urllib2.html –

+0

如果我使用urllib2然後urlencode將無法正常工作,它會給我錯誤,如果我簡單地傳遞這些參數,那麼它會給出錯誤。 –

+3

那你爲什麼不使用'urllib'和'urllib2'中的'urlocode'呢?或者你可以看看http://docs.python-requests.org/en/latest/# – filmor

回答

0

影片有權利。嘗試使用請求。功能示例:

def http_get(url, user=None, password=None, proxies=None, valid_response_status[httplib.OK], **kwargs): 
""" 
Performs a http get over an url 
@param url: the url to perfom get against 
@type url: str 
@param user: user if authentication required 
@type user: str 
@param password: password if authentication required 
@type password: str 
@param proxies: proxies if required 
@type proxies: dict 
@param valid_response_status: http response status code considered as valid 
@type valid_response_status: list of int 
@raise exception: if the response status code is not in valid_response_status list 
""" 
auth = HTTPBasicAuth(username=user, password=password) 
kwargs['proxies'] = proxies 
kwargs['auth'] = auth 
try: 
    LOGGER.debug("Performing http get over : %s" % url) 
    _request = requests.get(url, **kwargs) 
    if _request.status_code not in valid_response_status: 
     http_error_msg = '%s Error: %s' % (_request.status_code, _request.reason) 
     http_error = HTTPError(http_error_msg) 
     http_error.response = _request 
     raise http_error 
    return _request.content 
except: 
    LOGGER.error("Error while performing http get over : %s" % url) 
    raise