65.9K
CodeProject 正在变化。 阅读更多。
Home

基于RestSharp的Box.com云服务单页控制台应用程序

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013年4月8日

LGPL3

3分钟阅读

viewsIcon

30364

downloadIcon

512

本文介绍如何使用RestSharp SDK构建Box.com云服务的应用程序。

引言

本文将对那些打算为桌面应用程序使用Box.com云服务,并且面对众多可用功能和现有贡献而犹豫的开发者有所帮助。如果您是本文的读者,那么简单易用的“复制粘贴”代码正在等待您! :)

本文延续了以DropBox说明为开端的简短教程系列。

背景

如今,云服务是每个人都想使用的。加入流行的云群体看起来简单快捷。特定的云服务提供商文档页面通常包含大量信息,并且由于云的分布式特性,通常会指定自定义REST风格的API。这样的规范足以理解服务提供商提供的功能数量,但不会让我们更接近使用任何常规开发工具和现代编程语言的实际实现。

RestSharp SDK提供了许多已经实现的功能,例如OAuth v1和OAuth v2协议,REST协议等等,甚至还提供了一个框架,展示如何以原生风格使用RestSharp SDK。

在学习和使用应用程序之前,请确保您已经完成了以下步骤:注册Box.com并创建一个Box.com应用程序(即获取App密钥/App密钥对)。您可以在Box.com开发者资源这里阅读解释这些简单步骤的说明。

Using the Code

本文提供了一个完整的Microsoft Visual Studio 2010 Express应用程序,它能够获取OAuth v2授权码、用户批准、访问令牌,并检索用户的帐户信息,作为Box.com服务使用的一个常规示例。

让我们逐步了解应用程序中最有趣的部分。

配置应用程序

将您获得的App密钥/App密钥对放入下面的常量string中。这是重要的一步,也是唯一需要您贡献才能使其实际有效的部分代码。

private const string mc_apiKey = "YOUR_API_KEY";
private const string mc_appsecret = "YOUR_APP_SECRET";

获取授权码并获得用户的访问批准

此步骤对应于授权操作

//
// Get Authorization Code and an Approval from the User
//

var baseUrl = "https://www.box.com";

var client = new RestClient(baseUrl);

// Create a Callback URL
string sAuthorizationCallBackURL = string.Format(
    sLoopbackCallback,
    auth_GetRandomUnusedPort(), Assembly.GetEntryAssembly().GetName().Name
    );
    
var request = new RestRequest(
    string.Format(
    "/api/oauth2/authorize?response_type=code&client_id={0}&state=authenticated&redirect_uri={1}",
    mc_apiKey, sAuthorizationCallBackURL
    ), Method.POST);
    
bool bHasUserGrantedAccess = false;

var url = client.BuildUri(request).ToString();

// Set up a local HTTP server to accept authentication callback

string auth_code = null;
var resetEvent = new ManualResetEvent(false);
using (var svr = SimpleServer.Create(sAuthorizationCallBackURL, context =>
{
    var qs = HttpUtility.ParseQueryString(context.Request.RawUrl);
    auth_code = qs["code"];
    
    if (!string.IsNullOrEmpty(auth_code))
    {
        // The user has granted access
        bHasUserGrantedAccess = true;
    }
    
    // Resume execution...
    resetEvent.Set();
    
}))
{
    // Launch a default browser to get the user's approval
    System.Diagnostics.Process.Start(url);
    
    // Wait until the user decides whether to grant access
    resetEvent.WaitOne();    
}

if (false == bHasUserGrantedAccess)
{
    // The user has not granded access
    break;
}

string authorizationCode = auth_code;

获取访问令牌

此步骤对应于令牌操作

//
// Get Access Token
//

request = new RestRequest("/api/oauth2/token", Method.POST);

request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", authorizationCode);
request.AddParameter("client_id", mc_apiKey);
request.AddParameter("client_secret", mc_appsecret);

var response = client.Execute<AccessToken>(request);

if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
    break;
}

// Extract the Access Token

// output parameter:
accessToken = response.Data;

if (string.IsNullOrEmpty(accessToken.access_token) ||
    string.IsNullOrEmpty(accessToken.refresh_token) ||
    (0 == accessToken.expires_in))
{
    break;
}

刷新访问令牌(目前,即使实际服务使用持续时间很短,也必须每小时重复此过程)

此步骤对应于令牌操作

	//
	// Refresh the access token (should be done if the 1 hour passed 
	// since the last access token has been obtained)
	//
	// Please not, the step refresh would fail in case the 1 hour has not passed
	// That is why the code has been cut using the preprocessor
	//

#if USE_REFRESH_TOKEN
	request = new RestRequest("/api/oauth2/token", Method.POST);

	request.AddParameter("grant_type", "refresh_token");
	request.AddParameter("code", accessToken.access_token);
	request.AddParameter("client_id", mc_apiKey);
	request.AddParameter("client_secret", mc_appsecret);
	request.AddParameter("refresh_token", accessToken.refresh_token);

	response = client.Execute<AccessToken>(request);
	
	if (response.StatusCode != System.Net.HttpStatusCode.OK)
	{
		break;
	}

	// Extract the Access Token

	// output parameter:
	accessToken = response.Data;

	if (string.IsNullOrEmpty(accessToken.access_token) ||
		string.IsNullOrEmpty(accessToken.refresh_token) ||
		(0 == accessToken.expires_in))
	{
		break;
	}

#endif // USE_REFRESH_TOKEN

获取用户信息

此步骤对应于获取当前用户的资料操作

//
// Below is a sample how to access any Box service regular using the valid access token
//

baseUrl = "https://api.box.com";

client = new RestClient(baseUrl);

request = new RestRequest(string.Format("/{0}/users/me", mc_version), Method.GET);

request.AddParameter(
    "Authorization",
    string.Format("Bearer {0}", accessToken.access_token), ParameterType.HttpHeader);
    
var responseAccountInfo = client.Execute<AccountInfo>(request);

if (responseAccountInfo.StatusCode != System.Net.HttpStatusCode.OK)
{
    break;
}

AccountInfo accountInfo = responseAccountInfo.Data;

Console.WriteLine("Got access to the \"{0}\" account with ID=\"{1}\" and \"{2}\" e-mail. ",
    accountInfo.name,
    accountInfo.id,
    accountInfo.login);

关注点

本文的主要目标是为C#开发者提供一个完整的参考应用程序,以加快查找其工作方式、从何开始以及如何使其工作的过程。 :)

我希望我的微薄贡献能够帮助其他正在寻求此类帮助的开发者。

谢谢

我要感谢为本文提供背景支持的贡献者。

历史

  • 2013-04-05 初稿
© . All rights reserved.