For a side project I'm trying to do some analyses on the NS (Nederlandse Spoorwegen) data via the NS api.
strangely, getting the station info from http://webservices.ns.nl/ns-api-avt?station=Dordrecht works perfectly, but trying to get all stations from http://webservices.ns.nl/ns-api-stations results in a HTTPError.
Works:
import urllib2
from xml.etree import ElementTree
import datetime, time, sys
theurl = 'http://webservices.ns.nl/ns-api-avt'
username = 'username'
password = 'password'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
specificURL = 'http://webservices.ns.nl/ns-api-avt?station=Dordrecht'
xmlHandle = urllib2.urlopen(specificURL)
Does not work:
theurl = 'http://webservices.ns.nl/ns-api-avt'
username = 'username'
password = 'password'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
specificURL = "http://webservices.ns.nl/ns-api-stations"
xmlHandle = urllib2.urlopen(specificURL)
The two routines are identical, but yield different results. Am I missing something?
The Error code:
File "stations.py", line 32, in <module>
xmlHandle = urllib2.urlopen(specificURL)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized
(partially) Solved
A code, as simple as:
import requests
url = 'http://webservices.ns.nl/ns-api-stations-v2'
username = 'username'
password = 'password'
print(requests.get(url, auth=(username, password)).content)
works! For both the urls. Strange that the other way did not work for both, but only for one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.