从服务器而不是从浏览器

时间:2016-01-31 11:56:59

标签: python api http http-status-code-403

我正在尝试使用Python和urllib2访问Buxfer REST API。

问题是我收到以下回复:

urllib2.HTTPError: HTTP Error 403: Forbidden

但是当我通过浏览器尝试相同的调用时,它运行正常......

脚本如下:

username = "xxx@xxxcom"
password = "xxx"

    #############

def checkError(response):
    result = simplejson.load(response)
    response = result['response']
    if response['status'] != "OK":
        print "An error occured: %s" % response['status'].replace('ERROR: ', '')
        sys.exit(1)

    return response

base = "https://www.buxfer.com/api";
url  = base + "/login?userid=" + username + "&password=" + password;

req = urllib2.Request(url=url)
response = checkError(urllib2.urlopen(req))
token = response['token']

url  = base + "/budgets?token=" + token;
req = urllib2.Request(url=url)
response = checkError(urllib2.urlopen(req))
for budget in response['budgets']:
    print "%12s %8s %10.2f %10.2f" % (budget['name'], budget['currentPeriod'], budget['limit'], budget['remaining'])

sys.exit(0)

我也尝试过使用请求库但出现了同样的错误。 我要访问的服务器是ubuntu 14.04,任何有关解释或解决原因的帮助都将受到赞赏。

编辑:

这是完整的错误消息:

{                                                                                                            
  'cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>,                                               
  '_content': '                                                                                              
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">                                                       
    <html><head>                                                                                             
    <title>403 Forbidden</title>                                                                             
    </head><body>                                                                                            
    <h1>Forbidden</h1>                                                                                       
    <p>You don't have permission to access /api/login                                                        
    on this server.</p>                                                                                      
    <hr>                                                                                                     
    <address>Apache/2.4.7 (Ubuntu) Server at www.buxfer.com Port 443</address>                               
    </body></html>',                                                                                         
  headers': CaseInsensitiveDict({                                                                            
    'date': 'Sun, 31 Jan 2016 12:06:44 GMT',                                                                 
    'content-length': '291',                                                                                 
    'content-type': 'text/html; charset=iso-8859-1',                                                         
    'server': 'Apache/2.4.7 (Ubuntu)'                                                                        
  }),                                                                                                        
  'url': u'https://www.buxfer.com/api/login?password=xxxx&userid=xxxx%40xxxx.com',                           
  'status_code': 403,                                                                                        
  '_content_consumed': True,                                                                                 
  'encoding': 'iso-8859-1',                                                                                  
  'request': <PreparedRequest [GET]>,                                                                        
  'connection': <requests.adapters.HTTPAdapter object at 0x7fc7308102d0>,                                    
  'elapsed': datetime.timedelta(0, 0, 400442),                                                               
  'raw': <urllib3.response.HTTPResponse object at 0x7fc7304d14d0>,                                           
  'reason': 'Forbidden',                                                                                     
  'history': []                                                                                              
}             

编辑2 :( GoogleChrome浏览器中的网络参数)

Request Method:GET
Status Code:200 OK
Remote Address:52.20.61.39:443
Response Headers
view parsed
HTTP/1.1 200 OK
Date: Mon, 01 Feb 2016 11:01:10 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Frame-Options: SAMEORIGIN
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Cache-Controle: no-cache
Set-Cookie: login=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=buxfer.com
Set-Cookie: remember=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=buxfer.com
Vary: Accept-Encoding
Content-Encoding: gzip
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/x-javascript; charset=utf-8
Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Cookie:PHPSESSID=pjvg8la01ic64tkkfu1qmecv20; api-session=vbnbmp3sb99lqqea4q4iusd4v3; __utma=206445312.1301084386.1454066594.1454241953.1454254906.4; __utmc=206445312; __utmz=206445312.1454066594.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)
Host:www.buxfer.com
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36

编辑3:

我也可以通过我的本地pycharm控制台访问而没有任何问题,只是当我尝试从我的远程服务器执行此操作时...

1 个答案:

答案 0 :(得分:1)

可能需要执行POST而不是GET请求。大多数登录都以这种方式工作。

使用请求库,您需要

response = requests.post(
    base + '/login',
    data={
        'userid': username,
        'password': password
    }
)