Internet and cloud services programming overview (Android versus Windows Store apps)
[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]
Learn about key similarities and differences between Internet and cloud services programming models for Android and Windows Store apps.
Introduction
Remote data and storage APIs are a key need for most apps. Both Android and Windows 8 offer several networking options. Two that are covered here are networking capabilities for Internet content and web service capabilities for remote data access.
Top
Remote content access through networking
HTTP is the most widely accepted protocol for accessing content from remote networking locations like Internet websites. Both Android and the Windows Runtime offer HTTP client APIs for data downloads and uploads functionality.
Android HTTP client API
Developers can program to DefaultHttpClient or AndroidHttpClient, which are the extensions of Apache HttpClient implementation. HttpUrlConnection is a lightweight HTTP client suitable for most Android apps. The following code snippet example shows the use of various Android HTTP client APIs.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://www.bing.com/");
HttpResponse httpResp = httpClient.execute(httpGet);
HttpEntity bingPage = httpResp.getEntity();
if (bingPage != null) {
// Read the content by using bingPage.getEntity.
}
}
catch (Exception e) { // Handle any exceptions. }
AndroidHttpClient can be used in the preceding code by replacing new DefaultHttpClient()
with AndroidHttpClient.newInstance("test-app")
. AndroidHttpClient can't be used from the UI thread, so make sure to run the code on a background thread.
HttpUrlConnection is a lightweight HTTP client that is recommended in the latest versions of the Android API. Here is a code snippet example for using HttpUrlConnection.
try {
URL url = new URL("https://www.bing.com");
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
InputStream inStream = new BufferedInputStream(huc.getInputStream());
// Read from the stream and process the content.
}
catch (Exception e) { // Handle any exceptions. }
Windows 8 HTTP client API
For Windows Store apps, you use the System.Net and System.Net.Http namespaces in .NET for Windows Store apps. Specifically, we recommend using the HttpClient class.
Following is a code snippet example using the HttpClient class to get some Customer
objects from a web service.
class Customer
{
public Name { get; set; }
public City { get; set; }
}
using (var httpClient = new HttpClient()) {
var resp = await httpClient.GetAsync(new Uri(ApiRoot));
using (var stream = await resp.Content.ReadAsStreamAsync()) {
var djs = new DataContractJsonSerializer(typeof (List<Customer>));
var customerList = new ObservableCollection<Customer>((IEnumerable<Customer>)
djs.ReadObject(stream));
}
}
The customerList
in the preceding code can be directly databound to list-based UI widgets. Because the .NET Framework requires minimal code to translate HTTP responses to business objects, developers are saved from writing lots of response-parsing code. Also, the compiler uses the await keyword to create the needed asynchronous boilerplate code for scheduling the work on a background thread while at the same time preserving the natural code flow.
Top
Remote data access through web services
Many apps rely on web services to store app data on remote web servers. Android and Windows 8 have APIs for accessing web services. There are two primary web service types today: Representational State Transfer (REST) and SOAP. REST uses HTTP methods such as POST
, GET
, PUT
, and DELETE
. SOAP uses a descriptive wire format for HTTP message exchanges.
Android web services APIs
REST web service calls from Android apps can be made through DefaultHttpClient or HttpURLConnection objects that were previously mentioned. Here's a code snippet example that calls a REST web service by using DefaultHttpClient.
String restRequestURL ="https://www.contoso.com?produttype=2";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(restRequestURL);
ResponseHandler<String> stringHandler = new BasicResponseHandler();
String productList;
try {
productListJson = httpClient.execute(httpGetRequest,stringHandler);
JSONObject productListJObject = JSONObject(productListJson);
// Use JSONObject for further processing.
}
catch (Exception e) { }
JSONObject is not a strongly-typed domain object, so it requires object state access through property name literals, as shown in the following code snippet example.
productJObject = productListJObject.getJSONObject("93495");
productJOBject.getString("description");
Java API for XML Web Services (JAX-WS) is the name of a collection of Java classes for creating web service specifications (WS-*)-compliant SOAP web services on a web server as well as client bindings. You can use open-source packages such as kSOAP2 for Android to call SOAP-based web services from Android apps.
Windows 8 web services APIs
REST web services for Windows Store apps can be implemented on the server using ASP.NET and Windows Communication Foundation (WCF). ASP.NET is recommended for REST. ASP.NET only supports HTTP, while WCF supports TCP, HTTP, REST, and SOAP.
Here is the code snippet example for creating and calling an ASP.NET-based web service on Windows.
// Server code.
public class CustomerController : ApiController
{
// GET /api/person.
public IEnumerable<Customer> Get()
{
return new List<Customer>()
{
new Customer { Name="John", Company="Seattle" },
new Customer { Name="Jim", Company="New York" }
};
}
}
// Client code.
private const string ApiRoot = "https://localhost:18088/api/customer";
public async void Load() {
using (var httpClient = new HttpClient())
{
var resp = await httpClient.GetAsync(new Uri(ApiRoot));
using (var stream = await resp.Content.ReadAsStreamAsync())
{
var djs = new DataContractJsonSerializer(typeof (List<Customer>));
var Customers = new ObservableCollection<Customer>((IEnumerable<Customer>)
djs.ReadObject(stream));
// Customers is a strongly-typed C# object that can be databound to UI controls.
}
}
}
Converting an HTTP data payload into strongly-typed domain objects (such as Customer
in the preceding code) is supported by default in the Windows Runtime.
WCF is equivalent to JAX-WS for WS-*-compliant SOAP web services. The latest version of WCF also supports REST web services and can be directly called from Windows Store apps for certain WCF bindings. These bindings include BasicHttpBinding
, NetTcpBinding
, NetHttpBinding
, and CustomBinding
. WCF uses bindings to declare messaging behaviors, wire formats, and wire protocols.
Here is a code snippet example for creating a WCF service on a web server and calling it from a Windows Store app.
// Server code.
[DataContract]
public class Customer
{
[DataMember]
public string Name;
[DataMember]
public string Address;
}
[ServiceContract]
public class Customers {
[OperationContract]
public List<Customer> GetAllCustomers()
{
return new List<Customer>()
{
new Customer { Name = "john", Address="seattle" },
new Customer { Name = "ken", Address = "Chicago" }
};
}
}
// Client code.
async void GetCustomers()
{
// Adding a web service reference to the project generates a proxy automatically.
CustomerProxy.CustomersClient client = new CustomerProxy.CustomersClient();
ObservableCollection<CustomerProxy.Customer> customers =
await client.GetAllCustomersAsync();
// The customers collection can be databound directly to a grid UI control.
}
Microsoft Visual Studio can generate a strongly-typed proxy from a Web Services Description Language (WSDL) endpoint or a WSDL file. Microsoft Visual Studio only generates asynchronous proxies for Windows Store apps, which requires using the await keyword in calls to asynchronous methods, as shown by the call to the GetAllCustomersAsync method in the preceding code. The output is a strongly-typed Customer
collection that can be databound directly to a UI control, such as a grid, that can display a list of customers to the end user.
On the web server, WCF uses DataContract attributes for data payloads and ServiceContract attributes for endpoint generation. All of the messaging and serialization logic is generated by Visual Studio tools, so no boilerplate code is required to parse and call WCF web services.
Top
Cloud services integration
In a highly-distributed and interconnected app ecosystem, app platforms must provide not only their own cloud services but also be able to interoperate with other app platforms and third-party cloud services. Typically, apps have cloud integration requirements for things such as security, state management, push notifications, and social networking.
Android authentication with OAuth providers
Android apps can integrate with cloud-based OAuth providers for doing things such as discretionary sharing of social graphs and for implementing app security features. The following figure shows just a few of the OAuth providers that Android apps can use leverage for sign in and info sharing.
Windows 8 authentication with OAuth providers
Windows Store apps support integrating with OAuth providers including popular providers as shown in the following figure.
The following code snippet example shows authenticating with Facebook by requesting an authentication token from the Facebook OAuth service.
string clientID = "App_API_ID";
string oauthDialogUrl = @"https://www.facebook.com/dialog/oauth";
string returnUrl = @"https://www.facebook.com/connect/login_success.html";
string error = string.Empty;
try
{
String facebookURL =
string.Format(@"{0}/?client_id={1}&redirect_uri={2}&response_type=token",
oauthDialogUrl, clientID, Uri.EscapeDataString(returnUrl));
Uri oauthDialogUri = new Uri(facebookURL);
Uri returnUri = new Uri(returnUrl);
WebAuthenticationResult WebAuthenticationResult =
await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
oauthDialogUri,
returnUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
string authResponse = WebAuthenticationResult.ResponseData.ToString();
}
else
{
// Handle any error.
}
}
catch (Exception e)
{
// Handle any exception.
}
The OAuth dialog Uniform Resource Identifier (URI) uses the format as required by Facebook, as follows.
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID
&redirect_uri=https://www.facebook.com/connect/login_success.html
&response_type=token
Since Facebook expects a web browser to issue token requests, the WebAuthenticationBroker object hosts the authentication dialog box inside of a WebView control that renders web content with capabilities equivalent to Windows Internet Explorer. The token response from Facebook is available through the ResponseData property in the following format.
https://www.facebook.com/connect/login_success.html#access_token=YOUR_TOKEN&expires_in=4094
The token can be extracted and reused as proof of authentication as well as for subsequent social graph requests on the client or on the web server.
The WebAuthenticationBroker requires custom code for working with services such as Twitter, while it requires no custom code for Facebook.
Top