Networking

Use a simpler implementation of HTTP for all supported languages, easier network communication for your app, and new APIs for location-based mobile scenarios to develop versatile connected apps.

New or updated in Windows 8.1

New HTTP Client API

[Get the HTTPClient sample now.]

Windows 8.1 introduces Windows.Web.Http, the Windows Runtime namespace you use for Windows apps that connect to HTTP and Representational State Transfer (REST) web services. This new API provides full feature support across all supported languages, and replaces the HTTP API originally released for Windows 8 .

For basic request operations, the new API has a simple interface to handle the most common tasks and provides sensible defaults for authentication (AUTH) that apply to most scenarios. For more complex HTTP operations, additional capabilities include:

  • Methods for common verbs (DELETE, GET, PUT, and POST)

  • Ability to get, set, and delete cookies

  • Support for common authentication settings and patterns

  • HTTP Request progress info available on asynchronous methods

  • Access to Secure Sockets Layer (SSL) details on the transport

  • Ability to include customized filters in advanced apps

The Windows.Web.Http.Headers namespace supports creation of HTTP headers and cookies, which are then associated as properties with HttpRequestMessage and HttpResponseMessage objects.

Here's example code that shows how to use the new API to create a basic HTTP GET request for content on a web server returned as a string using the new API.


var uri = new Uri("http://example.com/datalist.aspx");
var httpClient = new HttpClient();

// Always catch network exceptions for async methods.
    httpClient.GetStringAsync (uri).done(function () {
            // Get completed operation.
       }, onError);


function onError(reason) {
    // Details in reason.Message and ex.HResult.       
}

// Once your app is done using the HttpClient object call close to 
// free up system resources (the underlying socket and memory used for the object)
// httpClient.close();


Custom HTTP request filters

With the web-request filter model supported by the new Windows.Web.Http.Filters namespace, it's easier than ever to make web requests that fit specific connectivity and security scenarios such as:

  • Handling authentication

  • Restricting access on metered networks

  • Using automatic retries after connection failures

  • Supporting modern programming techniques like mocking

It’s usually not difficult to handle a single network or security condition that you expect during a request, but handling many of them can be a challenge. You can use this new API to create a number of simple filters and then chain them as needed. So you can develop web-request capabilities for expected complexity without having to develop something equally complex.

HttpClient is the main class you use to send and receive requests over HTTP. It uses the HttpBaseProtocolFilter class to determine how to send and receive the data. So HttpBaseProtocolFilter is logically the end of any custom filter chain. Each HttpClient instance can have a different filter chain or pipeline, as shown here.

Drawing of an HTTP filter chain

To write a custom filter, you create a custom version of the IHttpFilter interface. Use the IHttpFilter.SendRequestAsync method to specify how the filter works. You can use C#, Visual Basic .NET, or C++ to write a filter. These filters can be called and used from any language that the Windows Runtime supports.

Here's example code for a filter that adds a custom header to HTTP requests and responses.



// A filter that adds a custom header to every Http request and response
public class PlugInFilter : IHttpFilter {
    private IHttpFilter innerFilter;

    public PlugInFilter(IHttpFilter innerFilter) {
        if (innerFilter == null) {
            throw new ArgumentException("innerFilter cannot be null.");
        }
        this.innerFilter = innerFilter;
    }

    // The SendRequest method where we add the custom headers
    public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request) {
        return AsyncInfo.Run<HttpResponseMessage, HttpProgress>(async (cancellationToken, progress) =>
        {
            request.Headers.Add("Custom-Header", "CustomRequestValue");
            HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);

            cancellationToken.ThrowIfCancellationRequested();

            response.Headers.Add("Custom-Header", "CustomResponseValue");
        return response;
        });
    }

    public void Dispose() {
        innerFilter.Dispose();
        GC.SuppressFinalize(this);
    }
}


To use this filter, pass its interface to the HttpClient(IHttpFilter) constructor when you create a new HttpClient object. To set up a filter chain, link new filters to a previous filter and to an HttpBaseProtocolFilter object at the end of the chain.

This example code shows how to create an HttpClient object and chain to a single custom filter.



internal static void CreateHttpClient(ref HttpClient httpClient)
{
    if (httpClient != null) {
        httpClient.Dispose();
    }

    // Extend HttpClient by chaining filters together
    // and then providing HttpClient with the configured filter pipeline.
    var basefilter = new HttpBaseProtocolFilter();

    // Adds a custom header to every request and response message.
    var myfilter = new PlugInFilter(basefilter);
    httpClient = new HttpClient(myfilter);

}



Background Transfer updates

[Get the Background Transfer sample now.]

Windows 8.1 introduces updates to Windows.Networking.BackgroundTransfer that further simplify file downloads and uploads for developers, leading to a better experience for end users.

  • The new BackgroundTransferGroup class makes it easy for your app to create these groups and to complete downloads and uploads in parallel, in serial, or based on priority. For example, when a user decides to download and watch episodes from a popular television series, your app can now prioritize the earliest episodes in the series or let the user choose which episode to download first.

  • Your app can now update its live tile or use toast notifications to provide status info to the user. You can configure these notifications by using new methods in the BackgroundDownloader and BackgroundUploader classes.

  • Background Transfer now automatically switches a download to a preferred network (for example, an unrestricted network) if the download can be resumed and is likely to take more than two minutes.

Real-time communication support for connected standby scenarios

[Get the Real-time communication sample now.]

Background networking now allows apps on the Windows lock screen to receive network packets even when the app is no longer running because the device is in a low-power state like connected standby. Updates include:

  • Real-time communications support for the new Windows.Web.Http API.

  • Support for quiet hours, a new feature in Windows 8.1.

  • A new notification for Voice over IP (VoIP) apps that lets them answer calls even while the screen is locked.

  • Four hardware slots to support connected standby on most network devices (the more common software slots do not support connected standby).

Connected standby updates

Connected standby is a special power state for Windows devices. It allows apps to perform limited connectivity tasks while the device screen is off and the device is in standby (low-power) state. Real-time communications and background networking use connected standby only when it's supported by the device's network adapter.

Windows 8.1 introduces these updates to connected standby, so that your apps can offer a connected experience that's responsive throughout the life cycle of a device:

  • Support for Ethernet and mobile broadband network adapters added (Wi-Fi adapters were already supported).

  • Support for more hardware slots for some network adapters that offer them (more slots means that more apps on the lock screen can use connected standby). The first 3 lock screen apps that register for a hardware slot can use a maximum of 3 hardware slots per app.

Geofence support

[Get the Geolocation sample now.]

Windows 8.1 introduces support for geofencing. Geofence allows an app to define a radius around a geographical point of interest and have the system alert the app when the device it's running on enters or exits that area. With this update to the Windows geolocation feature, your app can notify a user when friends are nearby, send a reminder to a user who is leaving work or home, or display coupons when the user is near certain stores.

The geofence capabilities in Windows 8.1 let you:

  • Create or remove one or more geofences, or areas of interest.

  • Set a notification to occur when entering or leaving a geofence.

  • Allow your geofence app to run in the background and continue to get geofence events by using the new background task LocationTrigger class.

  • Let your app receive geofence updates while on the lock screen.

The Windows.Devices.Geolocation.Geofencing namespace contains the classes you need to geofence. In general, you create one or more Geofence objects that define the areas of interest and the notification conditions. Then your app must handle the events that occur when the device enters or exits one of the defined areas. You can then test your app by using a simulator to simulate movement in and out of the geofence.

Wi-Fi Direct support

[Get the Wi-Fi Direct device sample now.]

You can use the new WiFiDirectDevice class to enumerate a list of Wi-Fi Direct devices within wireless range. These devices are associated with your PC using "Add a device" in the Devices section of your user settings. Your app can then create a network socket connection with any nearby Wi-Fi Direct device. Wi-Fi Direct is a new feature that enables Wi-Fi devices to connect easily with each other without requiring a wireless access point. It’s great for multimedia sharing or high-performance, connected games. For more information, see the Windows.Devices.WifiDirect namespace in the Windows Runtime API.

Note  You must enable the Proximity capability in your app manifest file in order to use the Wi-Fi Direct API.

 

 

Show:
© 2014 Microsoft. All rights reserved.