简体   繁体   中英

Rails: How to get a http request with header? (Product Hunt API)

I'm trying to use Product Hunt 's API to get its daily posts. This is what I endup with

task :fetch_product_hunt => :environment  do
  query = "http://api.producthunt.com/v1/posts"
  access_token = `My API Key`
  response = HTTParty.get(query,
                          :headers => {'Accept' => 'application/json',
                                       'Content-Type' => 'application/json',
                                       'Authorization' => access_token,
                                       'Host' => 'api.producthunt.com'}).body
  decode_response =  ActiveSupport::JSON.decode(response)
  puts decode_response
end

The problem is that I don't know how to specify the header for the get http request . And I'm getting {"status"=>"404", "error"=>"Not Found"} .

The docs are here: https://api.producthunt.com/v1/docs/posts/posts_index_get_the_posts_of_today

You have actually formatted the request properly to perform a GET . You don't need to set a header to do it; using the get method is what controls the HTTP verb.

Here's the proof. Here is a packet capture of what you have posted:

0x0040:  d47d 4745 5420 2f76 312f 706f 7374 7320  .}GET./v1/posts.
0x0050:  4854 5450 2f31 2e31 0d0a 4163 6365 7074  HTTP/1.1..Accept
0x0060:  3a20 6170 706c 6963 6174 696f 6e2f 6a73  :.application/js
0x0070:  6f6e 0d0a 436f 6e74 656e 742d 5479 7065  on..Content-Type
0x0080:  3a20 6170 706c 6963 6174 696f 6e2f 6a73  :.application/js
0x0090:  6f6e 0d0a 436f 6e6e 6563 7469 6f6e 3a20  on..Connection:.
0x00a0:  636c 6f73 650d 0a48 6f73 743a 2061 7069  close..Host:.api
0x00b0:  2e70 726f 6475 6374 6875 6e74 2e63 6f6d  .producthunt.com

Note that you can see the GET verb being used. This means that the problem is actually something else. Either the API documentation is not current or there is something wrong with your OAUTH token. It's hard to say because I would have expected a 401 rather than a 404 if the token were incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM