TIMEX
TIMEX

Reputation: 271674

How to send a HTTP Header request rather than HTTP URL in Python

I'm doing Oauth, and Linkedin needs me to send a "header" request instead of URL request (I have no idea what that means).

This is what someone says on Google:

If the library you are using isn't using HTTP headers for the authorization, you're not going to be able to access protected resources. Most OAuth libraries have an option that you can specify that will force it to use the header-based authorization.

Anyway, I specified it to headers! I know how to change it to headers. The only problem is...I don't know how to REQUEST stuff using the header method.

Before, without the header method:

url = oauth_request.to_url()
connection.request(oauth_request.http_method,url)
response = connection.getresponse()
s = response.read()

Now:

url = oauth_request.to_header()
connection.request(oauth_request.http_method,url)
response = connection.getresponse()
s = response.read()

But when I run it, I get this weird traceback.

File "/usr/lib/python2.6/httplib.py" in request
  874.             self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py" in _send_request
  891.         self.putrequest(method, url, **skips)
File "/usr/lib/python2.6/httplib.py" in putrequest
  807.                 if url.startswith('http'):

Exception Type: AttributeError at /g/
Exception Value: 'dict' object has no attribute 'startswith'

Upvotes: 0

Views: 1412

Answers (2)

joulesm
joulesm

Reputation: 642

Your connection.request method can take in HTTP headers:

connection.request(method, url, body = body, headers={'Authorization':header})

For OAuth, there are a bunch of fields that 'header' has:

OAuth realm="http://api.linkedin.com", oauth_consumer_key="##########", oauth_nonce="############", oauth_signature="########", oauth_signature_method="HMAC-SHA1", oauth_timestamp="#########", oauth_token="#########", oauth_version="1.0"

All the #### are things you need to have or generate.

Upvotes: 0

lprsd
lprsd

Reputation: 87077

I don't know about this particular oauth library you are using, so I can't comment on that.

But,

  • It can be clearly identified from the traceback, that oauth_request.to_header() returns a dictionary and not a string, that httplib.py expects.

  • The way to set authentication credentials in http headers is as follows:

from this question

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)

Hope it helps!

Upvotes: 2

Related Questions