0

I am trying to convert the following Java code to Python. Not sure what I am doing wrong, but I end up with an internal server error 500 with python.

Is the "body" in httplib.httpConnection method equivalent to Java httpentity? Any other thoughts on what could be wrong? The input information I collect is correct for sure.

Any help will be really appreciated. I have tried several things, but end up with the same internal server error.

Java Code:

HttpEntity reqEntitiy = new StringEntity("loginTicket="+ticket);
HttpRequestBase request = reMethod.getRequest(uri, reqEntitiy);
request.addHeader("ticket", ticket);
HttpResponse response = httpclient.execute(request);
HttpEntity responseEntity = response.getEntity();
StatusLine responseStatus = response.getStatusLine();

Python code:

 url = serverURL + "resources/slmservices/templates/"+templateId+"/options"
#Create the request
ticket = ticket.replace("'",'"')
headers = {"ticket":ticket}
print "ticket",ticket

reqEntity = "loginTicket="+ticket
body = "loginTicket="+ticket


url2 = urlparse.urlparse(serverURL)
h1 = httplib.HTTPConnection(url2.hostname,8580)
print "h1",h1

url3 = urlparse.urlparse(url)
print "url path",url3.path
ubody = {"loginTicket":ticket}
data = urllib.urlencode(ubody)
conn = h1.request("GET",url3.path,data,headers)
#conn = h1.request("GET",url3.path)
response = h1.getresponse()
lines = response.read()
print "response.status",response.status
print "response.reason",response.reason
Bono
  • 4,757
  • 6
  • 48
  • 77
  • 1
    You are doing *way too much low level work* here. Why not simply use `urllib2.urlopen()`? Or better still, install [`requests`](http://docs.python-requests.org/en/latest/) and use that instead. – Martijn Pieters Mar 09 '15 at 16:23
  • I see very little correlation between your Java code and the Python code. You are sending `loginTicket` in a request *body* but `GET` doesn't allow for request bodies. You need to use URL query parameters here. – Martijn Pieters Mar 09 '15 at 16:24
  • Thanks for the response Martin. urllib2 was my first choice. But I was not sure how to httpentity string - "loginTicket="+ticket through it. Can you suggest something for it ? – user3425922 Mar 09 '15 at 16:28

1 Answers1

0

You don't need to go this low level. Using urllib2 instead:

import urllib2
from urllib import urlencode

url = "{}resources/slmservices/templates/{}/options".format(
    serverURL, templateId)
headers = {"ticket": ticket}
params = {"loginTicket": ticket}
url = '{}?{}'.format(url, urlencode(params))

request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
print 'Status', response.getcode()
print 'Response data', response.read()

Note that the parameters are added to the URL to form URL query parameters.

You can do this simpler still by installing the requests library:

import requests

url = "{}resources/slmservices/templates/{}/options".format(
    serverURL, templateId)
headers = {"ticket": ticket}
params = {"loginTicket": ticket}

response = requests.get(url, params=params, headers=headers)
print 'Status', response.status
print 'Response data', response.content  # or response.text for Unicode

Here requests takes care of URL-encoding the URL query string parameters and adding it to the URL for you, just like Java does.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I used exactly identical code above, but tun into the error below. – user3425922 Mar 09 '15 at 17:00
  • @user3425922: there was a `)` missing in the first sample, now fixed. – Martijn Pieters Mar 09 '15 at 17:03
  • I used exactly identical code above, but run into the error below. I can access the url through the browser (I am logged into session). Thoughts ? ---- "C:\Users\student\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.2.2785.win-x86_64\lib\urllib2.py", line 531, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) – user3425922 Mar 09 '15 at 17:06
  • I had fixed the missing ) in the original code. This is a different error. I can access the url through the browser (am logged in session). So I am not sure, why I get the http error. – user3425922 Mar 09 '15 at 17:07
  • I don't know either, because I cannot see what status code the server returned for that exception to be raised. – Martijn Pieters Mar 09 '15 at 17:10
  • @user3425922: the exception has the status code; use `try...except urllib2.HTTPError as e: print e.code` to extract it. – Martijn Pieters Mar 09 '15 at 17:23
  • It is the same exception. Exception 500 which corresponds to internal server error. All 3 modules, "requests", urllib2" and httplib are ending in the same exception. My only guess is if httpEntity in java actually corresponds to something else in python. So far have tried passing that as params and also as body, with the same result. Thoughts ? I really appreciate it. – user3425922 Mar 09 '15 at 18:40
  • public static abstract enum RequestMethod { GET, POST, PUT; abstract HttpRequestBase getRequest(URI paramURI, HttpEntity paramHttpEntity); } – user3425922 Mar 09 '15 at 19:18
  • It takes in uri and params, that's about it. – user3425922 Mar 09 '15 at 19:18
  • @user3425922: I cannot find any reference to that class or methods, makes it rather impossible for me to help out. – Martijn Pieters Mar 09 '15 at 19:25
  • It might have to do with cookies. I can retrieve the session id successfully from the earlier part. If I have to add it to the above code, it will be added to header like,,,"Cookie":"session=12345678" correct ? – user3425922 Mar 09 '15 at 21:04
  • @user3425922: you can use a [`Session()` object](http://docs.python-requests.org/en/latest/user/advanced/#session-objects) and have `requests` automatically capture and handle cookies for you. – Martijn Pieters Mar 09 '15 at 21:09
  • Okay Solved !!!! The cookie name I was getting from the server in the earlier call was incorrect. Thanks a lot for your help. – user3425922 Mar 09 '15 at 21:58