SharePoint 2013 REST Services: Downloading a file and working with Json via the HttpClient

I was recently asked about how you would find and download a file using the HttpClient and REST.  I decided to try and accomplish the task in a good old fashion Console Application using the standard .NET libraries instead of the Windows Store this time and realized that even with my past experience and previous code to work from this was no small task and it was only with help from the three following sites I was able to come up with the code below. The lack of the Json classes in the Windows Store libraries makes working with REST responses far more involved, though a bit easier to leverage once you have all the pieces in place when working with a standard .NET application:

Json Serialization Tutorial:

http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET

Derive .NET classes for serialization from raw Json data:

http://json2csharp.com/

View Json Data in a structure format:

http://jsonviewer.stack.hu/

Once you get your Json responses to your REST API calls you need to take a look at them and create classes to feed to the JsonSerializer.  This leaves you with objects that perfectly mirror the Json data structure as you would view it in the jsonviewer for extracting data.   Once you have all that it’s pretty easy to call the REST API and retrieve the data you need to download files.

Of coarse, the Microsoft.SharePoint.Client library could do the same task in a fraction of the time, but I am often asked how to work with the REST services without using those libraries.

The CODE:

    public class JsonHelper
    {
        /// JSON Serialization
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
        /// JSON Deserialization
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }
    }

    //Custom Json Classes
    public class RootObject
    {
        public D d { get; set; }
    }
    public class D
    {
        public GetContextWebInformation GetContextWebInformation { get; set; }
        public List<Result> results { get; set; }
    }
    public class GetContextWebInformation
    {
        public int FormDigestTimeoutSeconds { get; set; }
        public string FormDigestValue { get; set; }
        public string LibraryVersion { get; set; }
        public string SiteFullUrl { get; set; }
        public string WebFullUrl { get; set; }
    }
    public class Result
    {
        public ContentType ContentType { get; set; }
        public string EncodedAbsUrl { get; set; }
        public string FileLeafRef { get; set; }
        public Folder Folder { get; set; }
        public int FileSystemObjectType { get; set; }
        public int Id { get; set; }
        public string ContentTypeId { get; set; }
        public string Title { get; set; }
        public int? ImageWidth { get; set; }
        public int? ImageHeight { get; set; }
        public string ImageCreateDate { get; set; }
        public object Description { get; set; }
        public object Keywords { get; set; }
        public string OData__dlc_DocId { get; set; }
        public int ID { get; set; }
        public string Created { get; set; }
        public int AuthorId { get; set; }
        public string Modified { get; set; }
        public int EditorId { get; set; }
        public object OData__CopySource { get; set; }
        public int? CheckoutUserId { get; set; }
        public string OData__UIVersionString { get; set; }
        public string GUID { get; set; }
    }

    class Program
    {
        static void Main()
        {

            string url = "https://sharepoint.site/";
            string filename = "2010-07-23 13.32.22.jpg"; ;
            string digest = "";
            HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
            client.BaseAddress = new System.Uri(url);
            string cmd = "_api/contextinfo";
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
            client.DefaultRequestHeaders.Add("ContentType", "application/json");
            client.DefaultRequestHeaders.Add("ContentLength", "0");
            StringContent httpContent = new StringContent("");
            HttpResponseMessage response = client.PostAsync(cmd, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                string content = response.Content.ReadAsStringAsync().Result;
                RootObject sp = JsonHelper.JsonDeserialize<RootObject>(content);
                digest = sp.d.GetContextWebInformation.FormDigestValue;
            }
            client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
            client.BaseAddress = new System.Uri(url);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
            client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
            client.DefaultRequestHeaders.Add("X-HTTP-Method", "GET");
            string uri = "_api/web/lists/GetByTitle('Your Pictures')/Items?$select=ID,FileLeafRef,EncodedAbsUrl&$filter=FileLeafRef eq '" + filename + "'";
            HttpResponseMessage response2 = client.GetAsync(uri).Result;
            response2.EnsureSuccessStatusCode();
            if (response2.IsSuccessStatusCode)
            {
                string listItems = response2.Content.ReadAsStringAsync().Result;
                RootObject sp = JsonHelper.JsonDeserialize<RootObject>(listItems);
                foreach (Result result in sp.d.results)
                {
                    MemoryStream stream = (MemoryStream)client.GetAsync(result.EncodedAbsUrl).Result.Content.ReadAsStreamAsync().Result;
                    using (FileStream fileStream = System.IO.File.Create(@"C:\" + result.FileLeafRef))
                    {
                        stream.WriteTo(fileStream);
                    }
                }
            }
            else
            {
                var content = response.Content.ReadAsStringAsync();
            }
        }
    }
Advertisements