2015-05-25 54 views
0

我想通過用戶的access_token在Facebook上獲取用戶詳細信息。 HTTPS需要啓用。如何在ruby中處理'HTTP會話已經打開'錯誤?

get '/fbdetails' do 
uri = URI('https://graph.facebook.com/me?access_token=CAACEdEose0cBAMF7kse5oFQyygDDgOZCMQFvddZBEskIdxiNlmWd2Mzx3lLWZCoZCJZCjXnMN08NLe8Ts8UJoOd9XjNrJ9QG5BsZC9ahB0h9NcdSDZA0LDdjfmtiXnmimyNZBTTxv7UT1ZBcz2vbKj2DYZAAGdoy7woJEcu1ZAoFpzcpaa47mz0DLwgNPY6PZA0Vrc7ZAT9snEZC6XdiUZAkgUZARvhBIxlltqEEelAZD') 
Net::HTTP.start(uri.host, uri.port, 
:use_ssl => uri.scheme == 'https').start do |http| 
    request = Net::HTTP::Get.new uri.request_uri 
    response = http.request 
    end 
    return response 
end 

這裏,IOError即HTTP會話已經打開。這種格式

需要JSON響應:

{ 
    "id": "10206515808233150", 
    "first_name": "Ashutosh", 
    "gender": "male", 
    "last_name": "Jha", 
    "link": "https://www.facebook.com/app_scoped_user_id/10206515808233150/", 
    "locale": "en_US", 
    "name": "Ashutosh Jha", 
    "timezone": 5.5, 
    "updated_time": "2015-02-17T16:38:08+0000", 
    "verified": true 
} 
+0

如何使用寶石考拉 - https://github.com/arsduo/koala – emaillenin

+0

雅這是一個簡單的方法。謝謝 –

回答

2

有你的代碼的兩個錯誤。

(1)您使用了兩次start方法,以至於發現「HTTP會話已經打開」錯誤。

Net::HTTP.start(uri.host, uri.port, 
:use_ssl => uri.scheme == 'https').start do |http|.... 

(2),錯過http.request

response = http.request 

的參數,以便你的代碼應該是:

uri = URI('https://graph.facebook.com/me?access_token=CAACEdEose0cBAMF7kse5oFQyygDDgOZCMQFvddZBEskIdxiNlmWd2Mzx3lLWZCoZCJZCjXnMN08NLe8Ts8UJoOd9XjNrJ9QG5BsZC9ahB0h9NcdSDZA0LDdjfmtiXnmimyNZBTTxv7UT1ZBcz2vbKj2DYZAAGdoy7woJEcu1ZAoFpzcpaa47mz0DLwgNPY6PZA0Vrc7ZAT9snEZC6XdiUZAkgUZARvhBIxlltqEEelAZD') 
Net::HTTP.start(uri.host, uri.port, 
:use_ssl => uri.scheme == 'https') do |http| 
    request = Net::HTTP::Get.new uri.request_uri 
    response = http.request request 
    #puts response.body 
    end 

您可以從ruby net/http library doc找到更多有用的信息。

+0

謝謝,這對我很有用。 –