如何在Ruby中的URL中添加id字段

时间:2016-01-06 15:52:41

标签: ruby-on-rails ruby

我需要添加一个字段(请参阅下面链接中的“id”)以向Google缩短API发出Ruby请求。

https://www.googleapis.com/urlshortener/v1/url?fields=id&key= {YOUR_API_KEY}

我会这样做吗?

 request.add_field('id', '')

或者这个

request.body = {'fields' => 'id', 'longUrl' => url, 'key' => 'kjdflsakjfslkf334'}.to_json

这是代码。不确定以上是否如何将ID添加到网址中的字段?

  require "net/https"
  uri = URI.parse('https://www.googleapis.com')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  request = Net::HTTP::Post.new("/urlshortener/v1/url")
  request.add_field('Content-Type', 'application/json')
  request.body = {'longUrl' => url, 'key' => 'kjdflsakjfslkf334'}.to_json
  response = http.request(request)

  d = JSON.parse(response.body)

  return d['id']

=================

更新:我根据下面的建议更改了代码(网址)。我现在得到了一个不同的错误。

        LogEntry.record(User.root_user, "The url inside and before shorten is: #{url}", LogEntry::ADMIN, url)
  require "net/https"
  uri = URI.parse('https://www.googleapis.com/urlshortener/v1/url')

  # Full control
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new(uri.request_uri)
  request["Content-Type"] = "application/json"
  request.body = {"fields" => "id", "longUrl" => url, "key" => "IzaSc8"}.to_json
  response = http.request(request)

   LogEntry.record(User.root_user, "The request sent to google shorten is : #{request.body}", LogEntry::ADMIN, request.body)
  d = JSON.parse(response.body)
  LogEntry.record(User.root_user, "The url inside shorten after google shorten is : #{d}", LogEntry::ADMIN, d)
  return d['id']

NEW ERROR(是的,我正在通过我启用的密钥):

{“error”=> {“errors”=> [{“domain”=>“usageLimits”,“reason”=>“dailyLimitExceededUnreg”,“message”=>“未经身份验证的每日限制使用超出。继续使用需要注册。“,”extendedHelp“=>”https://code.google.com/apis/console“}],”code“=> 403,”message“=>”超出未经身份验证的使用的每日限制。继续使用需要注册。“}}

1 个答案:

答案 0 :(得分:0)

你想要

response = Net::HTTP.post_form("/urlshortener/v1/url", 'fields' => 'id', 'key' => 'kjdflsakjfslkf334')

好的博客文章:http://www.rubyinside.com/nethttp-cheat-sheet-2940.html显示长短形式......