How to secure System.Net.Http.HttpClient connections (Windows Store apps using C#/VB and XAML)

Applies to Windows only

Secure System.Net.Http.HttpClient connections to a web service.

Note  The System.Net.Http and System.Net.Http.Headers namespace might not be available in future versions of Windows for use by Windows Store apps. Starting with Windows 8.1 and Windows Server 2012 R2, use Windows.Web.Http.HttpClient in the Windows.Web.Http namespace and the related Windows.Web.Http.Headers and Windows.Web.Http.Filters namespaces instead for Windows Store apps.

What you need to know

Technologies

Prerequisites

The following example in this topic is provided in C# using the .NET Framework 4.5. A basic understanding of HTTP requests as detailed in RFC 2616 is required.

To make HTTP requests in a Windows Store app using JavaScript and HTML, see Connecting to a web service (HTML).

Use the https: URI scheme

The HTTP Protocol defines two URI schemes:

  • http - Used for unencrypted connections.
  • https - Used for secure connections that should be encrypted. This option also uses digital certificates and certificate authorities to verify that the server is who it claims to be.

To encrypt your connection, use the https: URI scheme. For example:


   // Create a New HttpClient object.
   HttpClient client = new HttpClient();

   // use https: for the URI scheme
   HttpResponseMessage response = await client.GetAsync("https://www.contoso.com/");


Remarks

In this topic we reviewed how to secure System.Net.Http.HttpClient connections.

The following example changes one line in the code for the System.Net.Http.HttpClient sample to secure the connection and verify the server.

HttpClient secure connection sample


    HttpClient client = new HttpClient();

    try	
    {
      HttpResponseMessage response = await client.GetAsync("https://www.contoso.com/");
      response.EnsureSuccessStatusCode();
      string responseBody = await response.Content.ReadAsStringAsync();
      // Above three lines can be replaced with new helper method in following line
      // string body = await client.GetStringAsync(uri);

      httpClientSecure.DisplayStatus(responseBody);

    catch(HttpRequestException e)
    {
       httpClientSecure.DisplayStatus("Exception caught"+e.Message);
    }
    catch (Exception ex)
    {
       httpClientSecure.DisplayStatus(ex.ToString);
    }


Related topics

Other resources
Connecting to web services
How to configure network capabilities
How to connect using System.Net.Http.HttpClient
How to use System.Net.Http.HttpClient handlers
Reference
System.Net.Http
System.Net.Http.Headers
Windows.Web.Http
Windows.Web.Http.Filters
Windows.Web.Http.Headers
Samples
HttpClient Sample

 

 

Show:
© 2014 Microsoft