简体   繁体   中英

Python script on Ubuntu VM can't connect to twitter API

I am using Ubuntu 12 with VitualBox on top of a Windows XP PC. I am using a proxy to access the internet. I can browse those websites with Firefox, and for script below:

import urllib2
import json

proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)

#conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
print return_str

Everything goes well for code above, but for similar code as below is not working.

import urllib2
import json

proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)


response = urllib.urlopen('https://api.twitter.com/1.1/search/tweets.json?q=microsoft')
print json.load(response)

The error log is as below.

Traceback (most recent call last):
  File "print.py", line 12, in <module>
    conn = urllib2.urlopen('https://api.twitter.com/1.1/search/tweets.json?q=microsoft')
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
    return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 113] No route to host>

Please help me out. Thanks.

Try creating a https handler and see if that fixes the problem.

Change this line:

proxy = urllib2.ProxyHandler({'http': 'http://my-proxy-server:80'})

to

proxy = urllib2.ProxyHandler({'https': 'http://my-proxy-server:80'})  

and see if that works, since the Twitter API you are trying to access is over HTTPS.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM