2011-04-12 3 views
-2

facebookSampleASPNETApp를 다운로드했습니다. 나는 내가 어디에서 그것을 발견했는지 더 이상 모른다. 그러나 나는 그것이 정말로 멋지다라고 생각한다. 하지만 그것은 웹 응용 프로그램이고, 나는 ASP 웹 사이트를 만들고 있습니다.facebookAPI 사용 방법은 어디에서 찾을 수 있습니까?

이 샘플에서 사용 된 것과 동일한 코드를 사용하고 싶습니다. 이 샘플에서는 FacebookAPI.cs 및 JSONObject.cs와 같은 일부 클래스를 가져 오려고했지만 내 웹 사이트에서는 작동하지 않습니다. 어쩌면 비난 할 필요가 있을까요?

facebookSampleASPNETApp에는 두 개의 프로젝트가 있습니다. 하나는 FacebookAPI이고, 다른 하나는 facebookSampleASPNETapp 프로젝트입니다. 웹 사이트에서 다른 프로젝트를 가져올 수 없습니다. 그렇다면 어떻게 FacebookAPI를 사용할 수 있습니까? 어떤 도움이 아주 많이 감사합니다

/* 
* Copyright 2010 Facebook, Inc. 
* 
* Licensed under the Apache License, Version 2.0 (the "License"); you may 
* not use this file except in compliance with the License. You may obtain 
* a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
* License for the specific language governing permissions and limitations 
* under the License. 
*/ 

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Net; 
using System.IO; 
using System.Web; 
using System.Web.Script.Serialization; 

namespace Facebook 
{ 
enum HttpVerb 
{ 
    GET, 
    POST, 
    DELETE 
} 

/// <summary> 
/// Wrapper around the Facebook Graph API. 
/// </summary> 
public class FacebookAPI 
{ 
    /// <summary> 
    /// The access token used to authenticate API calls. 
    /// </summary> 
    public string AccessToken { get; set; } 

    /// <summary> 
    /// Create a new instance of the API, with public access only. 
    /// </summary> 
    public FacebookAPI() 
     : this(null) { } 

    /// <summary> 
    /// Create a new instance of the API, using the given token to 
    /// authenticate. 
    /// </summary> 
    /// <param name="token">The access token used for 
    /// authentication</param> 
    public FacebookAPI(string token) 
    { 
     AccessToken = token; 
    } 

    /// <summary> 
    /// Makes a Facebook Graph API GET request. 
    /// </summary> 
    /// <param name="relativePath">The path for the call, 
    /// e.g. /username</param> 
    public JSONObject Get(string relativePath) 
    { 
     return Call(relativePath, HttpVerb.GET, null); 
    } 

    /// <summary> 
    /// Makes a Facebook Graph API GET request. 
    /// </summary> 
    /// <param name="relativePath">The path for the call, 
    /// e.g. /username</param> 
    /// <param name="args">A dictionary of key/value pairs that 
    /// will get passed as query arguments.</param> 
    public JSONObject Get(string relativePath, 
          Dictionary<string, string> args) 
    { 
     return Call(relativePath, HttpVerb.GET, args); 
    } 

    /// <summary> 
    /// Makes a Facebook Graph API DELETE request. 
    /// </summary> 
    /// <param name="relativePath">The path for the call, 
    /// e.g. /username</param> 
    public JSONObject Delete(string relativePath) 
    { 
     return Call(relativePath, HttpVerb.DELETE, null); 
    } 

    /// <summary> 
    /// Makes a Facebook Graph API POST request. 
    /// </summary> 
    /// <param name="relativePath">The path for the call, 
    /// e.g. /username</param> 
    /// <param name="args">A dictionary of key/value pairs that 
    /// will get passed as query arguments. These determine 
    /// what will get set in the graph API.</param> 
    public JSONObject Post(string relativePath, 
          Dictionary<string, string> args) 
    { 
     return Call(relativePath, HttpVerb.POST, args); 
    } 

    /// <summary> 
    /// Makes a Facebook Graph API Call. 
    /// </summary> 
    /// <param name="relativePath">The path for the call, 
    /// e.g. /username</param> 
    /// <param name="httpVerb">The HTTP verb to use, e.g. 
    /// GET, POST, DELETE</param> 
    /// <param name="args">A dictionary of key/value pairs that 
    /// will get passed as query arguments.</param> 
    private JSONObject Call(string relativePath, 
          HttpVerb httpVerb, 
          Dictionary<string, string> args) 
    { 
     Uri baseURL = new Uri("https://graph.facebook.com"); 
     //relativePath = "/me"; 
     Uri url = new Uri(baseURL, relativePath); 
     if (args == null) 
     { 
      args = new Dictionary<string, string>(); 
     } 
     if (!string.IsNullOrEmpty(AccessToken)) 
     { 
      args["access_token"] = AccessToken; 
     } 
     JSONObject obj = JSONObject.CreateFromString(MakeRequest(url, 
                   httpVerb, 
                   args)); 
     if (obj.IsDictionary && obj.Dictionary.ContainsKey("error")) 
     { 
      throw new FacebookAPIException(obj.Dictionary["error"] 
               .Dictionary["type"] 
               .String, 
              obj.Dictionary["error"] 
               .Dictionary["message"] 
               .String); 
     } 
     return obj; 
    } 

    /// <summary> 
    /// Make an HTTP request, with the given query args 
    /// </summary> 
    /// <param name="url">The URL of the request</param> 
    /// <param name="verb">The HTTP verb to use</param> 
    /// <param name="args">Dictionary of key/value pairs that represents 
    /// the key/value pairs for the request</param> 
    private string MakeRequest(Uri url, HttpVerb httpVerb, 
           Dictionary<string, string> args) 
    { 
     if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET) 
     { 
      url = new Uri(url.ToString() + EncodeDictionary(args, true)); 
     } 

     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 

     request.Method = httpVerb.ToString(); 

     if (httpVerb == HttpVerb.POST) 
     { 
      string postData = EncodeDictionary(args, false); 

      ASCIIEncoding encoding = new ASCIIEncoding(); 
      byte[] postDataBytes = encoding.GetBytes(postData); 

      request.ContentType = "application/x-www-form-urlencoded"; 
      request.ContentLength = postDataBytes.Length; 

      Stream requestStream = request.GetRequestStream(); 
      requestStream.Write(postDataBytes, 0, postDataBytes.Length); 
      requestStream.Close(); 
     } 

     try 
     { 
      using (HttpWebResponse response 
        = request.GetResponse() as HttpWebResponse) 
      { 
       StreamReader reader 
        = new StreamReader(response.GetResponseStream()); 

       return reader.ReadToEnd(); 
      } 
     } 
     catch (WebException e) 
     { 
      throw new FacebookAPIException("Server Error", e.Message); 
     } 
    } 

    /// <summary> 
    /// Encode a dictionary of key/value pairs as an HTTP query string. 
    /// </summary> 
    /// <param name="dict">The dictionary to encode</param> 
    /// <param name="questionMark">Whether or not to start it 
    /// with a question mark (for GET requests)</param> 
    private string EncodeDictionary(Dictionary<string, string> dict, 
            bool questionMark) 
    { 
     StringBuilder sb = new StringBuilder(); 
     if (questionMark) 
     { 
      sb.Append("?"); 
     } 
     foreach (KeyValuePair<string, string> kvp in dict) 
     { 
      sb.Append(HttpUtility.UrlEncode(kvp.Key)); 
      sb.Append("="); 
      //NOTE: This line causes problems with access_token. The url encoding messes up the access_token, so for now I'm just adding it directly 
      //if the key == "access_token" 
      //sb.Append(HttpUtility.UrlEncode(kvp.Value)); 
      if (kvp.Key.ToLower() == "access_token") 
      { 
       sb.Append(kvp.Value); 
      } 
      else 
      { 
       sb.Append(HttpUtility.UrlEncode(kvp.Value)); 
      } 

      sb.Append("&"); 
     } 
     sb.Remove(sb.Length - 1, 1); // Remove trailing & 
     return sb.ToString(); 
    } 
} 
} 

:

다음은 FacebookAPI.cs 코드입니다!

+2

"작동하지 않습니까?" 작은 정보로 누구를 도와 줄 것이라고 어떻게 예상합니까? – Foole

답변

2

해당 주제의 official Facebook developer page을 확인하십시오. 그것은 당신을 잘 시작하게해야합니다. 이 페이지에서 같은 how to create an app on Facebook 상세한의 노하우를 찾을 수

편집 : 그냥 .NET and FB-authentication에 대한 블로그 게시물에 비틀 거렸다. 어쩌면 그것이 당신이 찾고있는 것일 수 있습니다.

+0

답변 해 주셔서 감사합니다. 페이스 북 앱을 등록했습니다. 페이 스북 그래프 API를 사용하는 방법을 안다. 현재로서는 내 게시물 방법을 직접 작성하고 있습니다. 하지만 그들은 항상 작동하지 않으며 나는 페이스 북에 물건을 게시하는 일관된 방법을 원합니다. 그래서 내가 facebookAPI 클래스 (내 질문에 표시)를 사용하고 싶습니다. 이 방법은 매우 훌륭하고 재사용이 가능합니다. 나는 그것이 나 자신을 보길 원하지 않는다는 것을 알지만, 나는 정말로 그랬고, 페이스 북에서이 파일을 사용할 수있는 ASP 웹 사이트에 대한 문서를 찾을 수 없다. 난 그냥 내 웹 사이트 에이 API 또는 클래스를 가져올 수있는 방법을 알아야합니다. 감사! – ThdK

+0

위의 편집을 참조하십시오. – froeschli

+0

Omg, 너무 늦게 편집을 보았습니다. 당신이 말한 블로그 게시물은 너무 좋습니다! 고맙습니다! – ThdK

관련 문제