Windows Azure(四-5):直接与服务器进行通信

 

上一篇:Windows Azure(四-4):云上的轻量数据库--Table Storage

 

我们已经学习了使用Windows Azure SDK所提供的StorageClient来使用Blob Storage, Queue Storage以及Table Storage的基本方法。

这次深入研究通过Blob Storage 直接与服务器进行通信。

准备工作

1. 确保你从Windows Azure 平台下载下载并安装了最新的Windows Azure开发工具;

2. 将使用List Blobs API,可简单看一下List Blobs

3. 为了测试我们的代码我们首先需要有一个已经创建的Container并且向其中添加至少一个Blob。(container名为helloworldcontainer

详情见:Windows Azure(四-2):云端的文件系统(Blob Storage)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;

namespace WT.Cloud.BlobStorageAPITest
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建Blob 客户端
            var account = CloudStorageAccount.DevelopmentStorageAccount;
            CloudBlobClient blobclient = account.CreateCloudBlobClient();

            // 检查container是否被创建,如果没有,创建container
            CloudBlobContainer container = blobclient.GetContainerReference("helloworldcontainer");
            container.CreateIfNotExist();

            // 新建一个CloudBlob,内容为"Hello World"
            CloudBlob cloudBlob = container.GetBlobReference("helloworldFile");
            //cloudBlob.UploadText("wt,love azure program");

             读取云端内容
            //Console.WriteLine("读取云端内容:");
            //string cloudContent = cloudBlob.DownloadText();

             删除blob
            //bool succeed = cloudBlob.DeleteIfExists();

            Console.Read();
   
        }
    }
}


运行上面项目练习目标

步骤

1. 确保Storage Emulator已经启动。我们可以找到管理器的进程手动启动或者让Visual Studio 2010帮助我们启动他。

2.创建Console项目,添加System.Web引用,使用该程序集发送http请求和接受HTTP消息

项目属性页里确认项目的Target framework的值是.NET Framework 4.NET Framework 3.5

3.添加代码

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Collections.Specialized; using System.Collections; using System.Web; // 发送http请求和接受HTTP消息 using System.Net; namespace WT.Cloud.BlobStorageTest { // 注意:一定要起云端服务;本文就是模拟客户端http请求云端服务; // 具体:可参见博文:Windows Azure(四-2):云端的文件系统(Blob Storage) // url:http://blog.csdn.net/xiaoyong322/article/details/6574057 // *创建一个Container和一个空Blob即可。 class Program { internal class CanonicalizedString { private StringBuilder canonicalizedString = new StringBuilder(); internal CanonicalizedString(string initialElement) { this.canonicalizedString.Append(initialElement); } internal void AppendCanonicalizedElement(string element) { this.canonicalizedString.Append("\n"); this.canonicalizedString.Append(element); } internal string Value { get { return this.canonicalizedString.ToString(); } } } private const string bloburi = @"http://127.0.0.1:10000/devstoreaccount1"; private const string accountname = "devstoreaccount1"; private const string key = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; private const string method = "GET"; static void Main(string[] args) { string AccountName = accountname; string AccountSharedKey = key; string Address = bloburi; string container = "helloworldcontainer"; // 创建请求字符串 string QueryString = "?restype=container&comp=list"; Uri requesturi = new Uri(Address + "/" + container + QueryString); string MessageSignature = ""; // 创建HttpWebRequest类 HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(requesturi.AbsoluteUri); Request.Method = method; Request.ContentLength = 0; Request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R")); Request.Headers.Add("x-ms-version", "2009-09-19"); // 开始创建签名 MessageSignature += "GET\n"; // Verb MessageSignature += "\n"; // Content-Encoding MessageSignature += "\n"; // Content-Language MessageSignature += "\n"; // Content-Length MessageSignature += "\n"; // Content-MD5 MessageSignature += "\n"; // Content-Type MessageSignature += "\n"; // Date MessageSignature += "\n"; // If-Modified-Since MessageSignature += "\n"; // If-Match MessageSignature += "\n"; // If-None-Match MessageSignature += "\n"; // If-Unmodified-Since MessageSignature += "\n"; // Range // CanonicalizedHeaders ArrayList list = new ArrayList(); foreach (string str in Request.Headers.Keys) { if (str.ToLowerInvariant().StartsWith("x-ms-", StringComparison.Ordinal)) { list.Add(str.ToLowerInvariant()); } } list.Sort(); foreach (string str2 in list) { StringBuilder builder = new StringBuilder(str2); string str3 = ":"; foreach (string str4 in GetHeaderValues(Request.Headers, str2)) { string str5 = str4.Replace("\r\n", string.Empty); builder.Append(str3); builder.Append(str5); str3 = ","; } MessageSignature += builder.ToString() + "\n"; } MessageSignature += GetCanonicalizedResourceVersion2(requesturi, AccountName); // 开始创建签名 byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature); System.Security.Cryptography.HMACSHA256 SHA256 =new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(AccountSharedKey)); // 创建Authorization HTTP消息头的值 String AuthorizationHeader = "SharedKey " + AccountName + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes)); // 把编码后的签名加入到Authorization HTTP消息头中 Request.Headers.Add("Authorization", AuthorizationHeader); // 获取返回消息 using (HttpWebResponse response = (HttpWebResponse)Request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { // 服务器返回成功消息 using (Stream stream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream)) { var s = sr.ReadToEnd(); // 输出返回消息 Console.WriteLine(s); } } } else { // 这里可以抛出异常信息 } } Console.ReadLine(); } static ArrayList GetHeaderValues(NameValueCollection headers, string headerName) { ArrayList list = new ArrayList(); string[] values = headers.GetValues(headerName); if (values != null) { foreach (string str in values) { list.Add(str.TrimStart(new char[0])); } } return list; } static string GetCanonicalizedResourceVersion2(Uri address, string accountName) { StringBuilder builder = new StringBuilder("/"); builder.Append(accountName); builder.Append(address.AbsolutePath); CanonicalizedString str = new CanonicalizedString(builder.ToString()); NameValueCollection values = HttpUtility.ParseQueryString(address.Query); NameValueCollection values2 = new NameValueCollection(); foreach (string str2 in values.Keys) { ArrayList list = new ArrayList(values.GetValues(str2)); list.Sort(); StringBuilder builder2 = new StringBuilder(); foreach (object obj2 in list) { if (builder2.Length > 0) { builder2.Append(","); } builder2.Append(obj2.ToString()); } values2.Add((str2 == null) ? str2 : str2.ToLowerInvariant(), builder2.ToString()); } ArrayList list2 = new ArrayList(values2.AllKeys); list2.Sort(); foreach (string str3 in list2) { StringBuilder builder3 = new StringBuilder(string.Empty); builder3.Append(str3); builder3.Append(":"); builder3.Append(values2[str3]); str.AppendCanonicalizedElement(builder3.ToString()); } return str.Value; } } } 

结果:(请求成功)

出现问题:

原因:没有启动云端服务。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
06-04

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值