Platinum Partner
mobile,rest,http,.net & windows,wp7

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

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.

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}