2

I was wondering how to make a GET request to geoserver 2.6 in Python.

import urllib2, json
url = 'http://localhost:8080/geoserver/rest/workspaces.json'  
authKey = 'admin:geoserver'
headers ={'Authorization': "Basic " + authKey}
params = {}
request = urllib2.Request(url, json.dumps(params), headers)

try:
    response = urllib2.urlopen(request, timeout=30).read()
    print json.loads(response)
except urllib2.HTTPError as e:
    print e
    print e.header
    print e.read()

with code above, I get HTTP Error 500: Server Error. If I set the value of authKey to '', then I get "HTTP Error 401: Full authentication is required to access this resource"

So how can I set up the request header with authorization?


Update:
I print e.headers in the exception, then I got:

Date: Tue, 17 Mar 2015 15:33:04 GMT
Content-Type: text/html;charset=ISO-8859-1
Cache-Control: must-revalidate,no-cache,no-store
Content-Length: 6639
Connection: close
Server: Jetty(7.6.13.v20130916)
4
  • does this help stackoverflow.com/questions/635113/…?
    – Ian Turton
    Commented Mar 17, 2015 at 14:28
  • not really. I have updated the header information when exception happens.
    – stevenhz
    Commented Mar 17, 2015 at 15:39
  • What does e.read() return? Perhaps the contents of the HTTPError provide some details. Commented Mar 17, 2015 at 16:18
  • e.read() returns: "Could not determine format. Try setting the Content-type header.". Then I specify the the 'Content-type':'application.json' in the headers variable, the 'print e' returns "HTTP Error 500: Server error". And 'print e.read()' returns nothing. Geoserver document says error 500 often donates a syntax error in the request.
    – stevenhz
    Commented Mar 18, 2015 at 21:05

2 Answers 2

3

I have a REST example that works on GWC, so I'll set it up so it's shared: https://gist.github.com/alexgleith/c39c3f520102c30e4dec

Here's the meaty bits:

url = baseURL + layer + '.json'
request = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (un, pw)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
request.add_header('Content-Type', 'application/json')
data = {'seedRequest':{'minX':[],'minY':[],'maxX':[],'maxY':[],'gridSetId':'EPSG:900913','zoomStart':00,'zoomStop':18,'format':'image/png','type':'seed','threadCount':2}}
data = json.dumps(data)
request.add_data(data)
req = urllib2.urlopen(request)
0

Thanks, alexgleith!

The problem in my simple code is:

authKey = 'admin:geoserver' request = urllib2.Request(url, json.dumps(params), headers)

should be replaced as:

authKey = base64.encodestring('%s:%s' % (un, pw)).replace('\n', '')
request = urllib2.Request(url)
for k in headers.keys():
    request.add_header(k, headers[k])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.