转载自:http://msdn.microsoft.com/en-us/library/bb463974.aspx
This Console application demonstrates the basic functionality of the Windows Live™ Contacts Representational State Transfer (REST) API.
C# Code Sample
To set up the project in Microsoft Visual Studio 2005
-
Open Microsoft Visual Studio® 2005.
-
On the File menu, click New, and then click Project. The New Project dialog box appears.
-
In the Project types pane, click Visual C#, and then click Windows.
-
In the Templates pane, click Console Application.
-
In the Name text box, type WLCDemo, and then click OK. Visual Studio 2005 creates a new project.
-
Replace the source code in the file Program.cs with the source code in the Example section for Program.cs. To do this, click Copy Code to place the code in the Windows Clipboard.
-
Open Program.cs from Solution Explorer, place your cursor anywhere in the file, and press CTRL+A.
-
Press CTRL+V to paste the code into the Visual Studio source file and overwrite the template-generated code.
-
Right-click anywhere in Solution Explorer, click Add, and then click New Item.
-
Under Templates, click XML File.
-
In the Name text box, type SamplePOST.xml, and then click Add.
-
In Solution Explorer, double-click SamplePOST.xml.
-
Replace the source code in the file with the source code in the Example section for SamplePOST.xml.
-
In Solution Explorer, right-click SamplePOST.xml, and then click Properties.
-
For the Copy to Output Directory property, click Copy Always.
-
Repeat steps 1 to 7, but replace all instances of SamplePOST.xml with SamplePUT.xml.
-
Press F5 to run the application in Debug mode.
Example
Program.cs
//THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED //TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //PARTICULAR PURPOSE. // //Copyright (C) 2007 Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Xml; using System.Xml.XPath; using System.IO; namespace WLCDemo { class Program { // Define account information. public const string strSampleWLID = "WLCRest@hotmail.com"; public const string strSampleLid = "8C06463EE2B3FBC5"; public const string strSampleHostName = "livecontacts.services.live.com"; // Authentication information public const string strSampleDelegatedToken = ""; public const string strSampleAuthHeaderValue = "DelegatedToken dt=/"" + Program.strSampleDelegatedToken + "/""; // Define configuration information. public const int iSamplePort = 443; public const string strSamplePOSTDataFile = "SamplePOST.xml"; public const string strSamplePUTDataFile = "SamplePUT.xml"; public const string strSampleErrorDataFile = "ErrorResponse.xml"; static void Main(string[] args) { bool bSuccess = true; bool bContactCreated = false; // Create starting point URI. This URI value changes after the contact // is created, modified, etc. UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = "HTTPS"; uriBuilder.Path = "/users/@L@" + strSampleLid + "/REST/LiveContacts/Contacts"; uriBuilder.Host = strSampleHostName; uriBuilder.Port = iSamplePort; string uriPath = uriBuilder.Uri.AbsoluteUri; // Create custom SSL handler ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { bool validationResult = true; return validationResult; }; // Create the contact. if (bSuccess) { bSuccess = SendHttpRequest(ref uriPath, "POST", HttpStatusCode.Created, strSamplePOSTDataFile, "created", null); bContactCreated = bSuccess; } // Retrieve the contact. if (bSuccess) { bSuccess = SendHttpRequest(ref uriPath, "GET", HttpStatusCode.OK, "ResultBeforeUpdate.xml", "retrieved", null); } // Update the contact. if (bSuccess) { bSuccess = SendHttpRequest(ref uriPath, "PUT", HttpStatusCode.NoContent, strSamplePUTDataFile, "updated", null); } // Retrieve the contact. if (bSuccess) { bSuccess = SendHttpRequest(ref uriPath, "GET", HttpStatusCode.OK, "ResultAfterUpdate.xml", "retrieved", null); } // Filter the contact by using the MapPoint predefined filter. if (bSuccess) { SendHttpRequest(ref uriPath, "GET", HttpStatusCode.OK, "ResultAfterFilter.xml", "filtered", "MapPoint"); } // Delete the contact. if (bContactCreated) { SendHttpRequest(ref uriPath, "DELETE", HttpStatusCode.NoContent, null, "deleted", null); } } // The SendHttpRequest method is the workhorse of this application. // It determines which type of HTTP request to send (e.g. GET, POST, etc.), // and how to handle the data it receives. // // The SendHttpRequest method uses the following parameters: // // ref string uriPath: // Specifies the URI that is used in the HTTP request. // string strRequestMethod: // Specifies the type of HTTP request. For example, "GET" or "POST". // HttpStatusCode expectedStatusCode: // Specifies the expected status code to be returned from the server. // string strDataFile: // For a "POST" or "PUT" request, this parameter specifies the file to load data from. // This data is then added to the body of the HTTP request. // For a "GET" request, this parameter specifies the file to write data to. // string strResultText: // Specifies the text to display in the results on the Console. // string strFilter: // Specifies the filter to use. // static bool SendHttpRequest(ref string uriPath, string strRequestMethod, HttpStatusCode expectedStatusCode, string strDataFile, string strResultText, string strFilter) { // Create HTTP request object. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriPath); // Append the filter to query string if a filter value is passed. if (strFilter != null) { request = (HttpWebRequest)WebRequest.Create(uriPath + "?Filter=" + strFilter); } // Add the authentication header request.Headers["Authorization"] = Program.strSampleAuthHeaderValue; // Only add the following Header if you can unzip/inflate the response automatically // otherwise the response will be unparsable and non XML request.Headers["Accept-Encoding"] = "gzip, deflate"; request.Headers["Pragma"] = "No-Cache"; request.CookieContainer = new CookieContainer(); // Set the HTTP request method. For example, this can be POST, GET, and so on. request.Method = strRequestMethod; // Set the HTTP content type - IMPORTANT - This must be exactly as written here and is REQUIRED request.ContentType = "application/xml; charset=utf-8"; // For POST or PUT requests, load data from the .xml file and write it to the request stream after the header. if (strRequestMethod.Equals("POST") || strRequestMethod.Equals("PUT")) { // Load data from file. XPathDocument doc = new XPathDocument(strDataFile); XPathNavigator nav = doc.CreateNavigator(); // Write data to request stream. XmlWriter writer = XmlWriter.Create(request.GetRequestStream()); nav.WriteSubtree(writer); writer.Flush(); // Close the request stream to release the resource. request.GetRequestStream().Close(); } // Invoke the HTTP request and get the response. HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException wex) { OutputException(wex); return false; } // Check response result. if (response.StatusCode != expectedStatusCode) { OutputUnexpectedResponse(response); return false; } // If this is a contact created by POST, update uriPath. if (strRequestMethod.Equals("POST")) uriPath = response.Headers[HttpResponseHeader.Location]; // If this is a GET request, write the data to an .xml file. if (strRequestMethod.Equals("GET")) OutputResponse(response, strDataFile); // Close the response to release the resource. response.Close(); // Display the results. Console.WriteLine("Contact " + strResultText + " successfully at:"); Console.WriteLine(uriPath); if (strRequestMethod.Equals("GET")) Console.WriteLine("Data written to " + strDataFile); Console.Write("Press any key to continue..."); Console.ReadLine(); Console.WriteLine(); return true; } // Define utility method for handling exceptions. static void OutputException(WebException wex) { Console.WriteLine(wex.ToString()); OutputUnexpectedResponse((HttpWebResponse)wex.Response); } // Define utility method for handling unexpected HTTP responses. static void OutputUnexpectedResponse(HttpWebResponse response) { if (response != null) { Console.WriteLine("Received an unexpected HTTP response"); Console.WriteLine("StatusCode: " + response.StatusCode.ToString()); OutputResponse(response, strSampleErrorDataFile); Console.WriteLine("OutputFile: " + strSampleErrorDataFile); Console.Write("Press any key to continue..."); Console.ReadLine(); } } // Define utility method for writing HTTP response to an .xml file. static void OutputResponse(HttpWebResponse response, string outputFileName) { if (response.ContentLength != 0) { FileStream outputStream = File.Create(outputFileName); XmlTextWriter writer = new XmlTextWriter(outputStream, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.IndentChar = ' '; XPathDocument doc = new XPathDocument(response.GetResponseStream()); XPathNavigator nav = doc.CreateNavigator(); nav.WriteSubtree(writer); writer.Flush(); writer.Close(); } } } }
SamplePost
SamplePost.xml
This is primary ABCH test account ABCH Int Mr. Paul Alan Roberts Jr. Aibiceiachi Ceshiban 1986-12-01T12:30:33Z May 8th Male GmtMinus8h Storage SDE address books WindowsLive Someone Personal dawei@hotmail-int.com true Business restfulabch@hotmail-int.com Personal +1(425)281-3700 Business +1(425)705-1400 true Business REDW-D2227 Windows Live Microsoft WeiRuanGongSi One Microsoft Way NE 148TH AVE Redmond King WA 98052 USA 38.0 116.3 false Personal 10711 167TH PL NE APT 115 Kirkland King WA 98123 USA 39.0 126.3 true Personal Future Public Front End URL http://contacts.live.com Business Public Front End URL http://contacts.live.com
SamplePut
SamplePut.xml
This is updated primary test account Updated ABCH Int UpdatedMr. UpdatedFirstName UpdatedMN UpdatedLast UpdatedJr. UpdatedAibiceiachi UpdatedCeshiban 1987-02-26 May 8th Female GmtMinus6h UpdatedStorage UpdatedSDE Updatedaddress books UpdatedWindowsLive UpdatedSomeone