I am trying to send a request to the Google Safe browsing Lookup API. It asks the user for a for a url for which he wants to do the look up. However there is some problem with the way I am sending the request because it keeps replying with Error Code 400. Kindly help.
import urllib
import urllib2
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
req_url = "https://sb-ssl.google.com/safebrowsing/api/lookup"
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("""<html>
<body>
<form action='' method='POST'>
<input type='text' name='url'>
<input type='submit' value='submit!!'>
</form>
</body>
</html>""")
def post(self):
post_data = {'client':'api',
'apikey':'My-API-Key',
'appver':'1.5.2',
'pver':'3.0',
'url':"%s"% self.request.get('url') }
data = urllib.urlencode(post_data)
try:
req = urlfetch.fetch(url = req_url,
payload = data,
开发者_开发问答 method = urlfetch.POST,
headers = {'Content-Type': 'application/x-www-form-urlencoded'})
if req.status_code == '200':
self.response.out.write("success")
self.response.out.write(req.content)
else:
self.response.out.write("Error code %s!!!"% req.status_code)
except urllib2.URLError, e:
self.response.out.write("Exception Raised")
handleError(e)
def main():
application = webapp.WSGIApplication([
('/', MainHandler)
],debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
You don't seem to be following the protocol for either the GET or POST method, but are doing something inbetween by passing what should be the GET params via POST.
Try this method:
import urllib
from google.appengine.api import urlfetch
def safe_browsing(url):
"""Returns True if url is safe or False is it is suspect"""
params = urllib.urlencode({
'client':'api',
'apikey':'yourkey',
'appver':'1.5.2',
'pver':'3.0',
'url': url })
url = "https://sb-ssl.google.com/safebrowsing/api/lookup?%s" % params
res = urlfetch.fetch(url, method=urlfetch.GET)
if res.status_code >= 400:
raise Exception("Status: %s" % res.status_code)
return res.status_code == 204
Which would work like:
>>> safe_browsing('http://www.yahoo.com/')
True
精彩评论