搜索推广API

    示例代码

    python代码示例如下:

    #!/usr/bin/python
    #encoding=utf8
    
    import os
    import sys
    import urllib
    import urllib2
    import json
    import hashlib
    import hmac
    import time
    import datetime
    from urllib import quote
    from urlparse import urlparse
    
    def gen_auth(access_key, secret_key, utc_time_str, url, method):
    	url_parse_ret = urlparse(url)
    	host = url_parse_ret.hostname
    	path = url_parse_ret.path
    	version = "1"
    	expiration_seconds = "1800"
    	signature_headers = "host"
    
    	# 1 Generate SigningKey
    	val = "bce-auth-v%s/%s/%s/%s" % (version, access_key, utc_time_str, expiration_seconds)
    	signing_key = hmac.new(secret_key, val, hashlib.sha256).hexdigest().encode('utf-8')
    
    	# 2 Generate CanonicalRequest
    	# 2.1 Genrate CanonicalURI
    	canonical_uri = quote(path)
    	# 2.2 Generate CanonicalURI: not used here
    	# 2.3 Generate CanonicalHeaders: only include host here
    	canonical_headers = "host:%s" % quote(host).strip()
    	# 2.4 Generate CanonicalRequest
    	canonical_request = "%s\n%s\n\n%s" % (method.upper(), canonical_uri, canonical_headers)
    
    	# 3 Generate Final Signature 
    	signature = hmac.new(signing_key, canonical_request, hashlib.sha256).hexdigest()
    	authorization = "bce-auth-v%s/%s/%s/%s/%s/%s" % (version, access_key, utc_time_str, expiration_seconds, signature_headers, signature)
    	print authorization
    	return authorization
    
    if __name__ == "__main__":
    	access_key = "AK"
    	secret_key = "SK"
    	url = "http://sem.baidubce.com/v1/cloud/PreviewService/getPreview"
    	method = "POST"
    	utc_time = datetime.datetime.utcnow()
    	utc_time_str = utc_time.strftime("%Y-%m-%dT%H:%M:%SZ")
    	auth = gen_auth(access_key, secret_key, utc_time_str, url, method)
    
    	header = {
        	'accept-encoding':'gzip, deflate',
        	'host':'sem.baidubce.com',
        	'content-type':'application/json',
        	'x-bce-date': utc_time_str,
        	'authorization': auth,
        	'accept':'*/*'
    	}
    	data = {"header": {"opUsername": "OPUSERNAME", "opPassword": "OPPASSWORD", "tgUsername": "TGUSERNAME", "tgPassword": "TGPASSWORD"},"body": {"keyWords": ["鲜花"],"device": 1, "region":1000}}
    	data = json.dumps(data)
    	request = urllib2.Request(url, data, header)
    	response = None
    	try :
        	response = urllib2.urlopen(request)
        	post_res_str = response.read()
        	print post_res_str
    	except urllib2.URLError, e:
        	print "URLError"
        	print e.code, e.reason
        	print e.read()
    	except urllib2.HTTPError, e:
        	print "HTTPError"
        	print e.code, e.reason
        	print e.read()

    您还可以直接下载代码示例进行参考:

    上一篇
    getPreview
    下一篇
    推广管理API