CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

HttpWebRequest Post to Viddler.

567 Views
Copy Code Show/Hide Line Numbers
const string vbCrLf = "\r\n";
 
        public string GetSessionId(string apiKey)
        {
            var queryString = GetQueryString(
                    new Dictionary<string, string> {
                        {"method", "viddler.users.auth"}
                        ,{"api_key", apiKey}
                        ,{"user", "XXX"}
                        ,{"password","XXXX"}
                    }
                );
            var response = RunApiGetCall(
                "http://api.viddler.com/rest/v1/"
                , queryString
                , new List<string> { "sessionid" }
                );
            return response["sessionid"];
        }
 
        
        private StringBuilder AddToFormContents(StringBuilder contents, PostDataParam param, string header)
        {
            if (param.Type == PostDataParamType.Field)
            {
                contents.Append(string.Format("Content-Disposition: form-data; name=\"{0}\"", param.Name) + vbCrLf);
                contents.Append(vbCrLf);
                contents.Append(param.Value);
            }
            else
            {
                contents.Append(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", param.Name, param.FileName) + vbCrLf);
                contents.Append(string.Format("Content-Type: {0}", param.ContentType) + vbCrLf);
                contents.Append(vbCrLf);
            }
            return contents;
        }
 
 
        public string GetFormContents(string boundaryValue, string header, List<PostDataParam> postParams)
        {
            bool isFirst = true;
            StringBuilder contents = new StringBuilder();
            foreach (var param in postParams)
            {
                if (isFirst)
                {
                    contents.Append("--" + boundaryValue);
                    contents.Append(vbCrLf);
                    contents = AddToFormContents(contents, param, header);
                    isFirst = false;
                }
                else
                {
                    contents.Append(header);
                    contents = AddToFormContents(contents, param, header);
                }
            }
            return contents.ToString();
        }
 
        public byte[] GetVideoBytes(string videoFilePath)
        {
            byte[] videoBytes = null;
            if (string.IsNullOrEmpty(videoFilePath) == true)
            {
                throw new ArgumentNullException("File Name Cannot be Null or Empty", "FilePath");
            }
            try
            {
                System.IO.FileInfo _fileInfo = new System.IO.FileInfo(videoFilePath);
                long _NumBytes = _fileInfo.Length;
                System.IO.FileStream _FStream = new System.IO.FileStream(videoFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FStream);
                videoBytes = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes));
                _fileInfo = null;
                _NumBytes = 0;
                _FStream.Close();
                _FStream.Dispose();
                _BinaryReader.Close();
 
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return videoBytes;
        }
 
        public string RunApiPostCall(string fileName, string videoFilePath, List<PostDataParam> postParams)
        {
            ServicePointManager.Expect100Continue = false;
            //System.Net.WebClient wc = new System.Net.WebClient();
            //var s = wc.DownloadString("http://www.cafepress.com");
 
            byte[] videoBytes = GetVideoBytes(videoFilePath);
            // Build the form to post
            ServicePointManager.Expect100Continue = false;
 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.viddler.com/rest/v1/");
 
            request.Method = "POST";
            request.KeepAlive = true;
 
            string boundaryValue = DateTime.Now.Ticks.ToString("x");
            string header = vbCrLf + "--" + boundaryValue + vbCrLf;
            string footer = vbCrLf + "--" + boundaryValue + "--" + vbCrLf;
 
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundaryValue);
 
            string contents = GetFormContents(boundaryValue, header, postParams); 
 
            byte[] BodyBytes = Encoding.UTF8.GetBytes(contents);
            byte[] footerBytes = Encoding.UTF8.GetBytes(footer);
 
            request.ContentLength = BodyBytes.Length + videoBytes.Length + footerBytes.Length;
 
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(BodyBytes, 0, BodyBytes.Length);
            requestStream.Write(videoBytes, 0, videoBytes.Length);
            requestStream.Write(footerBytes, 0, footerBytes.Length);
            requestStream.Flush();
            requestStream.Close();
 
            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }
        
        public Dictionary<string,string> RunApiGetCall(string uri, string queryString, List<string> responseFields)
        {
            HttpWebRequest request = WebRequest.Create(uri + queryString) as HttpWebRequest;
            request.Method = "GET";
            string response = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
            return GetResponseValueDictionary(response, responseFields);
        }
 
        public string GetQueryString(Dictionary<string, string> vals)
        {
            string result = null;
            bool first = true;
            foreach (var i in vals)
            {
                if (first == true)
                {
                    result += string.Format("?{0}={1}", i.Key, i.Value);
                    first = false;
                }
                else
                {
                    result += string.Format("&{0}={1}", i.Key, i.Value);
                }
            }
            return result;
        }
 
        public Dictionary<string, string> GetResponseValueDictionary(string response, List<string> responseFields)
        {
            XDocument xml = XDocument.Parse(response);
            var result = new Dictionary<string, string>();
            foreach (var key in responseFields)
                result.Add(key, xml.Descendants(key).FirstOrDefault().Value);
            return result;
        }
 
 
//CALLING Code:
 
public Dictionary<string,string> Upload(string fileName, string filePath, string apiKey)
        {
            string uri = "http://api.viddler.com/rest/v1/";
            var postDataParams = new List<PostDataParam> {
                 new PostDataParam("method", "viddler.videos.upload", PostDataParamType.Field)
                ,new PostDataParam("api_key", apiKey, PostDataParamType.Field)
                ,new PostDataParam("sessionid", GetSessionId(apiKey), PostDataParamType.Field)
                ,new PostDataParam("title", "Wildlife Video", PostDataParamType.Field)
                ,new PostDataParam("tags", "mytags", PostDataParamType.Field)
                ,new PostDataParam("make_public", "1", PostDataParamType.Field)
                ,new PostDataParam("description", "So good!", PostDataParamType.Field)
                ,new PostDataParam("file", filePath, fileName, PostDataParamType.File, "video/x-ms-wmv")
            };
            var responseFields = new List<string> { "id", "title", "description", "url", "thumbnail_url" };
            var response = RunApiPostCall(fileName, filePath, postDataParams);
            return GetResponseValueDictionary(response, responseFields);
        }
 
by Eric Veal
  November 20, 2010 @ 2:04pm

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate