`

ruby 调用restful接口示例

    博客分类:
  • RUBY
 
阅读更多
链接参数中添加token
def self.query_products_list
      url = "#{ Settings.aikang_host }/api/v1/sku/instoreCAS?token=#{ Settings.aikang_token }"
      begin
        resp = HTTParty.get(url)
      rescue
        {}
      end
    end


headers中添加Authorization,body中也添加账号密码
def self.stock(sku = [])
      url = "#{Settings.aladdin_host}/index.php/rest/V2/product/stock"
      resp = HTTParty.post(url, body: {sku: sku}.to_json, headers: request_header)
end

# 产品新增
    def self.create
      url = "#{Settings.aladdin_host}/index.php/rest/V2/product/new"
      resp = HTTParty.get(url, headers: request_header)
    end

    def self.order(orders)
      url = "#{Settings.aladdin_host}/index.php/api/http/order"
      secret_token = "Bearer " + Digest::MD5.hexdigest(Settings.aladdin_user_id.to_s + Settings.aladdin_company_code.to_s + Settings.aladdin_access_token.to_s).to_s
      headers = {'Authorization' => secret_token, 'Auth-Code' => Settings.aladdin_company_code.to_s, 'Content-Type' => 'application/json', 'User-Agent' => "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
      body = {user: {ald_user_id: Settings.aladdin_user_id.to_s, ald_user_email: Settings.aladdin_user_email.to_s}, orders: orders}
      puts body.to_json
      puts url
      puts headers
      resp = HTTParty.post(url, body: body.to_json, headers: headers)
      JSON.parse resp
    end

private

    def self.request_header
      {'Authorization' => "Bearer #{Settings.aladdin_access_token}", 'Content-Type' => 'application/json'}
    end


body中使用账号和key
module Api
  module Baidu

    def self.get_access_token
      url = "https://aip.baidubce.com/oauth/2.0/token"
      body = {grant_type: 'client_credentials', client_id: Settings.baidu_ocr_api_key, client_secret: Settings.baidu_ocr_secret_key}
      resp = HTTParty.post(url, body: body)
      resp.parsed_response['access_token']
    end

    def self.ocr_idcard(base64_code_image, side = :front)
      url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
      body = { access_token: get_access_token, detect_direction: true, id_card_side: side, image: base64_code_image, detect_risk: true }
      resp = HTTParty.post(url, body: body, headers: {'Content-Type' => 'application/x-www-form-urlencoded'})
      resp.parsed_response
    end

    def self.ocr_business_license(base64_code_image, detect_direction = false)
      url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
      body = { access_token: get_access_token, image: base64_code_image, detect_direction: detect_direction }
      resp = HTTParty.post(url, body: body, headers: {'Content-Type' => 'application/x-www-form-urlencoded'})
      resp.parsed_response
    end

  end
end


使用账号密码
module Api
  module Dibai

    def self.query_products(current_page, pagesize)
      resp = HTTParty.post("#{Settings.dibo_host}/api/get_products_list", body: {curpage: current_page, pagesize: pagesize}.merge(identity))
      begin
        JSON.parse resp
      rescue
        {"state" => false, "data" => [], "message" => "接口异常", "count" => 0, "pages" => 0}
      end
    end

    def self.query_price(cas)
      resp = HTTParty.post("#{Settings.dibo_host}/api/instant_stock", body: {key_word: cas}.merge(identity))
      begin
        JSON.parse resp
      rescue
        {"state" => false, "packing_count" => 0, "data" => [], "message" => "接口异常"}
      end
    end

    private

    def self.identity
      {username: Settings.dibo_username, password: Settings.dibo_password}
    end

  end

end


添加时间参数的直接url+账户id
def self.query_products(startdate, current_page = 1, pagesize = 10000)
      key = Digest::MD5.hexdigest(startdate + 'jkchemical').upcase
      url = "#{Settings.bailingwei_host}/WebService/ThirdPartyPlatform/ThirdPartyPlatformServiceHandler.ashx?key=#{ key }&startDate=#{ startdate }&pageIndex=#{ current_page }&pageSize=#{ pagesize }&thirdPartyPlatformId=6823432af42d244d8926f"
      res = HTTParty.get(url)
      begin
        JSON.parse res
      rescue
        {}
      end
end


在body中加md5内容密码参数验证
# 产品查询
    def self.query_product(cas)
      url = "#{Settings.macklin_host}/api/attachs/products"
      body = {attachs_code: Settings.macklin_username, timestamp: Time.now.to_datetime.strftime("%Q"), cas: cas.to_s.strip}
      body[:signcode] = signature(body)
      begin
        resp = HTTParty.post(url, body: body)
        resp["msg"]["items"]
      rescue
        []
      end
end

# 签名
    def self.signature(params)
      str = params.keys.sort.map{|k| params[k]}.join('').to_s + Settings.macklin_password.to_s
      Digest::MD5.hexdigest str
    end



url中,查询信息+密码后再md5加密的key
def self.query_product(product_no)
      key = "#{ Settings.meryer_secret }KEYWYeAdcaDXQproductCode#{ product_no }#{ Settings.meryer_secret }"
      sign = Digest::MD5.hexdigest(key).upcase
      url = "#{ Settings.meryer_host }/api/getpro.ashx?KEY=WYeAdcaDXQ&productCode=#{ product_no }&SIGN=#{ sign }"
      begin
        resp = HTTParty.get(url)
        JSON.parse resp
      rescue
        {}
      end
 end


时间token加到headers
module Api
  module Qichacha

    def self.get_enterprise_detail(keyword)
      daily_max_count = Lookup.find_by(code: :qichacha_daily_request_max_count)&.name.to_i
      counter = Counter.find_or_create_by(usage: "http://i.yjapi.com/ECIV4/GetDetailsByName", entity_type: "Employee", entity_id: 1, key: Time.now.strftime("%Y%m%d000000"))
      if counter.count < daily_max_count
        url = "http://api.qichacha.com/ECIV4/GetDetailsByName?key=#{Settings.qichacha_key}&keyword=#{keyword.to_s.strip}"
        timespan = Time.now.to_i.to_s
        token = Digest::MD5.hexdigest(Settings.qichacha_key.to_s + timespan + Settings.qichacha_secret_key).upcase
        resp = HTTParty.get(url, headers: {"Token" => token, "Timespan" => timespan})
        counter.incr! if resp["Status"].to_i == 200
        return resp
      else
        return { "Status" => "over limit"}
      end
    end

  end
end

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics