Posting data to the web from windows phone 7

There can be lot of ways to post data from the windows phone 7. The example shows the way to upload to the tumblr using WebClient class.


WP7-Mango.jpg

On the first release of windows phone 7 sdk,  most of the functions on WebClient are not available. Very few (only 4 operations are possible) are available.   Only asynchronous operation are permitted. This makes sense because  UI thread don't get blocked while sending or downloading data and they want to force developers to make use of asynchronous operation while transmitting data to/from the internet. Posting form data, uploading files, downloading files are not straightforward but you can send byte array to the server with OpenWriteAsync method , means you can send/upload any kind of data. Available functions on WebClient

  • DownloadStringAsync
  • OpenReadAsync
  • OpenWriteAsync
  • UploadStringAsync

Not available functions

  • DownloadData
  • DownloadDataAsync
  • DownloadFile
  • DownloadFileAsync
  • DownloadString
  • OpenRead
  • OpenWrite
  • UploadData
  • UploadDataAsync
  • UploadFile
  • UploadFileAsync
  • UploadString
  • UploadValues
  • UploadValusAsync

Lets use the UploadStringAsync method to send form data to the server from the phone 7 application. Only you have to manipulate the header (Content-Type)  and just send the formated string data. See the code lines below. 

 

Example code to send form data to the tumblr to create new regular post.

		private void Upload()
        {
            WebClient webClient = new WebClient();
            webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var   uri = new Uri("http://www.tumblr.com/api/write", UriKind.Absolute);
            StringBuilder postData = new StringBuilder();
            postData.AppendFormat("{0}={1}", "email", HttpUtility.UrlEncode("your email id"));
            postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode("secret"));
            postData.AppendFormat("&{0}={1}", "type", HttpUtility.UrlEncode("regular"));
            postData.AppendFormat("&{0}={1}", "title", HttpUtility.UrlEncode("hello this is regular text from phone 7 app"));

            webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
            webClient.UploadProgressChanged += webClient_UploadProgressChanged;
            webClient.UploadStringAsync(uri, "POST", postData.ToString());

        }

        void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            Debug.WriteLine("completed");
        }

        void webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            Debug.WriteLine(string.Format("Progress: {0} ",e.ProgressPercentage));
        } 
blog comments powered by Disqus