Mobile Zone is brought to you in partnership with:

Henry Lee is founder of NewAgeSolution.Net and is passionate about the technology. He is also the author of the book Beginning Windows Phone 7 Development 2nd edition from Apress (http://bit.ly/wp7apress2nd). He works with various Fortune 500 companies delivering mobile applications and rich internet applications. He recently formed start-up company called ToeTapz.com focusing his energy on delivering mobile applications to the consumers. In his spare time, he dedicates his effort to help his .NET community by delivering sessions at the technology events. He enjoys talking with other technologist about current trends in the technology and sharing business insights with fellow colleagues. Often you will find Henry at local cigar bar enjoying a cigar and a drink trying to come up with next big mobile application. Henry is a DZone MVB and is not an employee of DZone and has posted 9 posts at DZone. You can read more from them at their website. View Full User Profile

Windows Phone 7 and Making HTTPS REST API Calls with Basic Authentication

07.06.2011
| 10944 views |
  • submit to reddit
Recently, I have been busy implementing the REST API in Microsoft Azure using Windows Azure with WCF 4 and Routing mechanisms. The reason for choosing to implement REST is because of interoperability between multiple platforms that we have to support (iPhone, and Android). Here are some of the reasons why from our experience:

 

  1. Although there are third party components in iPhone and Android to support basic http soap we found it simpler to use a REST API.
  2. Dealing with HTTPS + Basic Http + WCF has not been developer friendly when it comes to developing against it. For example, if you implement custom authentication you must implement it in HTTPS secure transport over the user name but many times the development environment is not really setup to do HTTPS. You can use self signed certificates but you will quickly find that in Silverlight you will get endpoint Not Found error. This is because your code must validate the untrusted certificate. A good example of this is when you try to connect using IE to a self signed HTTPS site and it prompts you if you want to continue. Same thing happens in your code which you must handle and unfortunately I found out that in Windows Phone 7 Silverlight this is not supported and making it impossible to work with self signed cert. But with REST you simply use HTTP and when you are in production you switch the endpoint to HTTPS without any extra effort. If you are not using Windows Phone 7 you can over come using self signed cert by using below code:
  3. public static void SetCertificatePolicy()
    
    {
    
        ServicePointManager.ServerCertificateValidationCallback +=
    
        RemoteCertificateValidate;
    
    }
    
     
    
    private static bool RemoteCertificateValidate(object sender,
    
        X509Certificate cert, X509Chain chain, SslPolicyErrors error)
    
    {
    
        // trust any certificate!!!
    
        return true;
    
    }
    
  4. If we were ever to expose our endpoints to the public to be used then I think it makes it simpler to use a REST API since our methods are not very complex.
  5. There is not extra overhead from SOAP headers - we have to deal with making it ideal for Azure since you get charged by bandwidth.

In the following section you will learn how to make REST API calls in Silverlight.

How to make REST API call in Windows Phone 7?

You can choose to use HttpWebRequest and HttpWebResponse but I found it much simpler to use WebClient. Here is an example of REST POST call.

string url = “http://some url”;

 

WebClient req = new WebClient();

req.Credentials = new NetworkCredential(UserName, Password);

req.Headers["Content-type"] = “text/xml”;

req.UploadStringCompleted += (s, e) =>

{

    if (e.Error == null)

    {

        // Do Something with e.Result

    }

};

 

req.UploadStringAsync(new Uri(url), “POST”

    , DtoSerializer.GetString<MyDto>(myDto)); 

In the above code there are a couple things you need to make note of. Credentials, which you can use NetworkCredential for passing basic authentication, and setting Content-type to text/xml for posting XML. To post xml you will need to serialize your object using DataContractSerializer as shown in code below:

using System.Xml;

using System.IO;

using System.Runtime.Serialization;

using System;

using System.Text;

 

namespace Common

{

    public class DtoSerializer

    {

        public static T GetObject<T>(string xml)

        {

            if (string.IsNullOrEmpty(xml))

            {

                throw new ArgumentNullException(“xml”);

            }

            DataContractSerializer ser = new DataContractSerializer(typeof(T));

            return (T)ser.ReadObject(XmlReader.Create(new StringReader(xml)));

        }

 

        public static byte[] GetBytes<T>(T obj)

        {

            if (obj == null)

            {

                throw new ArgumentNullException(“obj”);

            }

 

            DataContractSerializer ser = new DataContractSerializer(typeof(T));

            using (MemoryStream msSerialized = new MemoryStream())

            {

                ser.WriteObject(msSerialized, obj);

                msSerialized.Flush();

                byte[] byteSerialized = msSerialized.ToArray();

                return byteSerialized;

            }

        }

 

        public static string GetString<T>(T obj)

        {

            byte[] array = GetBytes<T>(obj);

            return Encoding.UTF8.GetString(array, 0, array.Length);

 

        }

    }

}

You can also use above code to de-serialize the XML you GET from REST calls as show in code below:

string url = “https://your REST url”;

 

WebClient req = new WebClient();

req.Credentials = new NetworkCredential(UserName, Password);

req.DownloadStringCompleted += (s, e) =>

    {

        if (e.Error == null)

        {

            if (!string.IsNullOrEmpty(e.Result))

            {

                this.CurrentMyDto = DtoSerializer.GetObject<myDto>(e.Result);

            }

        }

    };

req.DownloadStringAsync(new Uri(url));

 

Conclusion

In this blog you learned about making REST API calls from your Windows Phone 7 application with Basic Authentication.

References
Published at DZone with permission of Henry Lee, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)