Thursday, 3 July 2014

How to call API using Windows.Web.Http.HttpClient

public async Task<HttpResponseMessage> GetAsync(Uri uri, string contentType = "application/json")
        {
            Logx.Info("HttpManager.GetAsync(" + uri + ", " + contentType + ')');
            HttpClient httpClient = GetHttpClient();
            HttpResponseMessage response = null;
            HttpMediaTypeHeaderValue mthv;
            HttpStringContent content;

            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
            httpClient.DefaultRequestHeaders.Add(ServiceConstants.HEADER_USER_AGENT, "P2PWindows");
            httpClient.DefaultRequestHeaders.Add(ServiceConstants.HEADER_API_VERSION, "1.0");
            httpClient.DefaultRequestHeaders.Add(ServiceConstants.HEADER_OS, "windows");

            mthv = new HttpMediaTypeHeaderValue(contentType);
            content = new HttpStringContent(string.Empty);
            content.Headers.ContentType = mthv;
            string data = string.Empty;
            try
            {
                response = await httpClient.GetAsync(uri);
            }
            catch (Exception e)
            {
                Logx.LogException(e, "HttpManager.GetAsync(" + uri + ", " + contentType + ')');
                // Check if task was cancelled
                var tce = e as TaskCanceledException;
                if (tce != null)
                {
                    if (TaskStatus.Canceled.Equals(tce.Task.Status))
                    {
                        // Task was cancelled
                        throw tce;
                    }
                }
            }

            return response;
        }

No comments:

Post a Comment