首先获取access_token
更其他接口一样,获取token需要2个参数, appid、appsecret,需要先添加应用
http://ai.baidu.com/docs#/Auth/top
def get_access_token
now = Time.now
now = now.to_i
client = HttpClient.new(@access_token_url, @timeout, @skip_verify_ssl)
data = client.get_json('baidu_access_token.json')
expire_seconds = data.blank? ? '' : data['expire']
access_token = nil
# 过期时间为空或小于记录的时间
if expire_seconds.blank? || expire_seconds < now
get_info = client.post('token', '', params: { grant_type: 'client_credentials', client_id: @client_id , client_secret: @client_secret })
unless get_info['access_token'].nil?
access_token = get_info['access_token']
expire_seconds = now + 2592000
data = {
access_token: access_token,
refresh_token: get_info['refresh_token'],
scope: get_info['scope'],
session_key: get_info['session_key'],
session_secret: get_info['session_secret'],
expire: expire_seconds
}
data_json = JSON.generate(data)
client.set_json('baidu_access_token.json', data_json)
end
else
access_token = data['access_token']
end
access_token
end
获取标签接口
http://ai.baidu.com/docs#/NLP-API/a1dae901
url需要参数access_token, 同时需要传递2个参数,title、content, 目前只支持gbk,我使用的是utf8,所以需要转码
参数 | 类型 | 描述 | 是否必填 |
---|---|---|---|
title | string | 文章标题(GBK编码),最大80字节 | 必填 |
content | string | 文章内容(GBK编码),最大65535字节 | 必填 |
def get_tag(title, content)
access_token = get_access_token
client = HttpClient.new(@tag_url, @timeout, @skip_verify_ssl)
tag_params = {
'title' => title,
'content' => content
}
tag_json = JSON.generate(tag_params)
tag_json = tag_json.encode('GBK','utf-8',{:invalid => :replace, :undef => :replace, :replace => '?'})
get_info = client.post('keyword', tag_json, params: { access_token: access_token })
res = Array.new
unless get_info['items'].blank?
res = get_info['items']
end
res
end
同样的,获取到的结果也需要转码