Exporting data to Google example

static void Main()
{
   string userId = "23492384698234029827";
   string deviceId = "Communergy.CurrentCost128.Home";          
   string url = string.Format("https://www.google.com/powermeter/feeds/user/{0}/{0}/variable/{1}.d1/durMeasurement", userId, deviceId);


   string auth = "CI2JxY-FxDk6_EJGPXejIkF";
   string xmlEntry = @"
   <entry xmlns="http://www.w3.org/2005/Atom" meter="http://schemas.google.com/meter/2008">
       <meter:starttime uncertainty="'1.0'">2010-04-21T13:30:00.000Z</meter:starttime>
       <meter:endtime uncertainty="'1.0'">2010-04-21T13:45:00.000Z</meter:endtime>
       <meter:quantity uncertainty="'0.001'" unit="'kW">0.642</meter:quantity>
   </entry>";        

   var ret = PostXml(url, xmlEntry, auth);
}


public static string PostXml(string url, string xml, string authToken)
{
   string response = string.Empty;
   try
   {
       //turn the xml into bytes
       var bytes = System.Text.Encoding.ASCII.GetBytes(xml);
       //create HttpWebRequest
       var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);          
       httpWebRequest.Method = "POST";
       httpWebRequest.ContentLength = bytes.Length;

       //set the required content type
       httpWebRequest.ContentType = "application/atom+xml";
       //set the token to the authorization header
       string authSubHeader = string.Format("AuthSub token=\"{0}\"", authToken);
       httpWebRequest.Headers.Add("Authorization", authSubHeader); 
             
       //write  the xml bytes to the request stream
       var requestStream = httpWebRequest.GetRequestStream();
       requestStream.Write(bytes, 0, bytes.Length);
       requestStream.Close();
       var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();              
       {
           //Get response stream
           using (var responseStream = httpWebResponse.GetResponseStream())
           {                      
               using (var xmlReader = new XmlTextReader(responseStream))
               {
                   response = xmlReader.ReadOuterXml();
               }
           }
       }
       httpWebResponse.Close();
   }
   catch (WebException we)
   {
            
       throw new Exception(we.Message);
   }
   catch (Exception ex)
   {
       throw new Exception(ex.Message);
   }
   return response;
}

Last edited Apr 14, 2010 at 10:10 PM by riotgibbon, version 3

Comments

No comments yet.