0

我正在尝试通过他们的 api 访问纽约公共图书馆的数字馆藏。

我用来拨打电话的红宝石代码是:

require 'sinatra'
require 'pp'
require 'httparty'


    get '/' do
        url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
        uri = URI.parse(url)
        http = Net::HTTP.new(uri.host, uri.port)

        headers = { "Authorization" => "Token token=mytoken" }
        request = Net::HTTP::Get.new(uri.request_uri, headers)
        response = http.request(request)
        puts response
        @response = response.body
        erb :index
    end

所以,有几个问题:

  1. 这不会产生任何结果,终端中的 puts 响应没有返回任何内容,甚至没有错误消息。我究竟做错了什么?

  2. 无论如何,如何在 uri 字符串的末尾附加查询?通过添加一个?其次是查询?所以,例如,?leonardodavinci

4

1 回答 1

1

推荐你在 irb 命令提示符下玩,例如

irb [enter]

好像没有授权?我最终得到=> nil了自己:

irb(main):003:0> require 'sinatra'
=> true
irb(main):004:0> require 'pp'
=> true
irb(main):005:0> require 'httparty'
=> false
irb(main):006:0> url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
=> "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
irb(main):007:0>   uri = URI.parse(url)
=> #<URI::HTTP:0x9826744 URL:http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json>
irb(main):008:0>  http = Net::HTTP.new(uri.host, uri.port)
=> #<Net::HTTP api.repo.nypl.org:80 open=false>
irb(main):009:0> headers = { "Authorization" => "Token token=mytoken" }
=> {"Authorization"=>"Token token=mytoken"}
irb(main):010:0> request = Net::HTTP::Get.new(uri.request_uri, headers)
=> #<Net::HTTP::Get GET>
irb(main):011:0> response = http.request(request)
=> #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>
irb(main):012:0> puts response
#<Net::HTTPUnauthorized:0x9938a74>
=> nil
irb(main):013:0> 
于 2013-05-25T02:19:45.983 回答