Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Mobile Zone
Free Resource

Recently, I have been busy implementing a REST API in Microsoft Azure using Windows Azure with WCF 4 and the Routing mechanism. 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 just 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 an 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 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, 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:
public static void SetCertificatePolicy()

{

    ServicePointManager.ServerCertificateValidationCallback +=

    RemoteCertificateValidate;

}

 

private static bool RemoteCertificateValidate(object sender,

    X509Certificate cert, X509Chain chain, SslPolicyErrors error)

{

    // trust any certificate!!!

    return true;

}
  1. If we were ever to expose our endpoints to the public to be used then I think it makes simpler to use REST API since out methods are not very complex.
  2. There is not extra overheads of SOAP header we have to deal making it ideal for Azure since you get charged by bandwidth.

In 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 above code there are couple thing you need to make note of. Credentials which you can use NetworkCredential for passing basic authentication. 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.




Topics:

Published at DZone with permission of Henry Lee, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}